AngularJS: Manipulate the $scope of an unknown $el

2019-08-29 05:56发布

问题:

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" />

Here is the directive:

.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));

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();

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.

回答1:

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);
        }
    };
});

See forked plunk: http://plnkr.co/edit/DZwTgrVNeLIbLXryscPy