Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to communicate between directive instances

I have two instances of a directive. Is there a way communicate between the two instances? Or can I set a global variable that all instances will share the same value.

I have tried to store the value in a service. When the value in one instance change, then other instances will be manually updated. But I am not sure whether this is the best way to it or not.

Thanks.

like image 859
user2434202 Avatar asked Sep 05 '13 14:09

user2434202


1 Answers

The directive factory itself is a singleton. Anything you declare outside of the definition object will be global to all instances. As each instance has it's own scope, instance-specific data should go in the scope. So, something like this:

angular.module("myApp", [])

.directive("myDir", function() {
    var myGlobal = 0;

    return {
        template: '<div>Global: {{getGlobal()}}, Local: {{local}} -- <a href="" ng-click="increment()">Increment</a></div>',
        scope: {},
        link: function(scope, element, attrs) {
            scope.local = 0;
            scope.increment = function() {
                scope.local++;
                myGlobal++;
            }
            scope.getGlobal = function() {
                return myGlobal;
            }
        }
    }
});

http://jsfiddle.net/7YwDS/

like image 60
dnc253 Avatar answered Nov 09 '22 02:11

dnc253