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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With