AngularJS - Using local variables inside directive

angularjs-directive

Solution

The init and local variables need to be declared within the link function, not in the directive declaration, which will be shared with all instances.

//JS
app.directive('myDir', function($timeout) {

    function link(scope, el, attrs) {
        var data, _el;

        function init(){
            _el.text(data);
        }

        _el = el;
        data = attrs.myDir;
        $timeout(init,500);
    }
    return {
        restrict: 'A',
        link: link
    };
});

See http://jsbin.com/kosiw/1/edit

Problem

I'm having trouble understanding how directives js scope works. I mean it looks like local variables declared in the main directive function are shared among all instances of the directive. Eg. ``` // HTML <ul> <li my-dir="1"></li> <li my-dir="2"></li> <li my-dir="3"></li> </ul> //JS .directive('myDir', function($timeout) { var data, _el; function init(){ _el.text(data); } function link(scope, el, attrs) { _el = el; data = attrs.myDir; $timeout(init,500); } return { restrict: 'A', link: link }; }); ``` In the above example I'll get only the last element populated with the last value because `_el` will each time be assigned a new element. Here you have a plnkr of the above: http://plnkr.co/edit/NXV6w4MZbROhnZ524wvx?p=preview What should I do instead?

Original source