How can I listen for an element attribute change in an Angular directive?
here plunker, it covers pretty well what I'm trying to do.
I have a directive! isolated volume ! with an attribute that is intended to be modified
<div ng-init="environment='natural'">
<input ng-model=environment>
<chameleon env="{{ environment }}"></chameleon>
</div>
I want my directive to respond to global scope changes:
angular.module('app', []).directive('chameleon', function () { return {
template: 'I am {{ color }}',
scope: {} // isolated
,link: function (scope, element, attrs) {
scope.$watch('env', function () {
scope.color = getColor();
});
function getColor () {
switch (attrs.env) {
case 'excited': return 'red';
...
case 'natural':
default: return 'green';
}
}
/* here I need something similar to this not-working code :
* element.on('attributeChange', function () {
* scope.env = attrs.env
* });
*/
}
}});
I know I can use an isolated scope to bind environment values ββlike
scope: {
env: '='
}
but I really need to have an independent component as the attribute value env
will not only be changed from the model.
feel free to unblock my plunker.
+3
source to share