Consider the following scenario.
There are two directives which is independent of each other and I want to share the scope between these two directives. Since they are not nested, I cant use a controller in the directives to share the scope. So I have created a service and injected the service to both of these directives.
So when the value of the service is changed in one directive, I need the same to be updated in the other directive. How can I achieve this? I want this done right, the angular way, with no anti-patterns.
This is what I have tried so far
.directive('d1', ['cData', function() {
return {
link: function() {
// this watch is not working
scope.$watch( function() {
return cData.Value;
}, function(newValue, oldValue) {
alert(newValue);
})
}
}
})
.directive('d2', ['cData', function() {
return {
link: function() {
element.on('click', function() {
cData.Value = false
scope.$digest();
});
// A watch here is working, I have commented it out
/*scope.$watch( function() {
return cd.showStatus;
}, function(newValue, oldValue) {
alert(newValue)
})*/
}
}
}])
.service('cData', function() {
this.Value = false;
})
I am updating the value of the service in click event of directive d2
and I need to trigger the watch in the directive d1
. May be this is not working as the scopes are different for two directives. How can I achieve this, any help is greatly appreciated.
UPDATE
Template for directive d1
template : '<div ng-class="{show:cData.Value==true}"></div>'
To update {show:cData.Value==true}
I have to again call scope.$apply() in the event listener of directive d1
Hope this is the right approach.
You are on the right path but, I would recommend using $broadcast
instead of adding a new $watch
. Adding a new watcher is more of a local scope solution (in my point of view at least). So it all boils down to sharing data between two independent objects. You can achieve this like so:
.directive('d1', ['cData', function() {
return {
link: function(scope) {
// this watch is not working
scope.$on('data:changed', function(e, data) {
alert(data);
}
/*
scope.$watch( function() {
return cData.Value;
}, function(newValue, oldValue) {
alert(newValue);
}) */
}
}
})
.directive('d2', ['cData', '$rootScope', function() {
return {
link: function() {
element.on('click', function() {
$rootScope.$broadcast('data:changed', { value: false });
// cData.Value = false
// scope.$digest();
});
// A watch here is working, I have commented it out
/*scope.$watch( function() {
return cd.showStatus;
}, function(newValue, oldValue) {
alert(newValue)
})*/
}
}
}])
From my point of view it's the cleanest way to achieve communication between independent objects/directives without much hassle. And the code is pretty clean and decoupled.
What do you think?
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments