AngularJS:处理未知元素$的$范围 [英] AngularJS: Manipulate the $scope of an unknown $element

查看:183
本文介绍了AngularJS:处理未知元素$的$范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新建角。
我创建了贯穿整个项目全球使用指令(属性)。我使用的是本地存储功能,我的目的是使该元素,对其中的属性位于,相应地改变它的值/文本。下面是HTML:

New to Angular. I'm creating a directive (attribute) for global use through the whole project. I'm using a local storage function and my intention is to have the element, on which the attribute is situated, change its value/text accordingly. Here is the HTML:

<input type="email" name="username" placeholder="Email Address" ng-model='username' loadstorage="USERNAME" />

下面是指令:

.directive("loadstorage", function (localStorage) {
        return function ($scope, $element, attrs) {
            $scope.$element = localStorage.get(attrs.loadstorage); 
        }
});

你可以想像这是行不通的。所以,我需要的是一个方法来处理调用该功能的元素的范围。
我试过到目前为止:

As you can imagine this doesn't work. So what I need is a way to manipulate the scope of the element that is calling the function. What I tried so far is:

$element.val(localStorage.get(attrs.loadstorage));

它的工作原理,但只有当我删除元素的NG-模式,遗憾的是我需要在项目的其他用途。

It works but only when I remove the ng-model of the element, unfortunately I need it for other purposes in the project.

angular.element($element).scope();

有了这个,我访问的范围,但不能处理它。以下是我在谈论的plunker例如: http://plnkr.co /编辑/ FScDaj4YDIae8ZEs9ucx?p = preVIEW
任何帮助将是AP preciated。

With this I access the scope but cannot manipulate it. Here is a plunker example of what I'm talking about: http://plnkr.co/edit/FScDaj4YDIae8ZEs9ucx?p=preview Any help would be appreciated.

推荐答案

您的指令可能应该操纵通过 ngModel 控制器(该值的文档):

Your directive should probably manipulate the value through the ngModel controller (docs):

.directive("loadstorage", function (localStorage) {
    return {
        require: ["ngModel"],
        link: function(scope, element, attrs, controllers) {
            var ngModel = controllers[0],
                val = localStorage.get(attrs.loadstorage);
            element.val(val);
            ngModel.$setViewValue(val);
        }
    };
});

请参阅分叉普拉克: http://plnkr.co/edit/DZwTgrVNeLIbLXryscPy

这篇关于AngularJS:处理未知元素$的$范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆