The best way to communicate between instances of the directive

I have two example directives. Is there a way to communicate between two instances? Or I can set a global variable that all instances will have the same value.

I tried to keep the value in the service. When the value in one instance changes, other instances will be updated manually. But I'm not sure if this is the best way or not.

Thanks.

+8
angularjs instance directive
source share
1 answer

The factory directive itself is single. Everything that you declare outside the definition object will be global for all instances. Because each instance has its own scope, instance data must fall within 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/

+11
source share

All Articles