Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Using local variables inside directive

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?

like image 302
mettjus Avatar asked Jul 15 '14 09:07

mettjus


People also ask

What is attrs in AngularJS?

scope is an AngularJS scope object. element is the jqLite-wrapped element that this directive matches. attrs is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values. controller is the directive's required controller instance(s) or its own controller (if any).

What is restrict option in directive?

restrict is for defining the directive type, and it can be A (Attribute), C (Class), E (Element), and M (coMment) , let's assume that the name of the directive is Doc : Type : Usage. A = <div Doc></div>

What is AngularJS used for?

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. AngularJS's data binding and dependency injection eliminate much of the code you would otherwise have to write.


1 Answers

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

like image 160
rchawdry Avatar answered Oct 19 '22 23:10

rchawdry