0

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 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.