javascript - How can I listen an element's attribute change in an Angular directive? -
here's plunker, pretty exposes i'm trying do.
i have directive ! isolated scope ! attribute intended changed
<div ng-init="environment='natural'"> <input ng-model=environment> <chameleon env="{{ environment }}"></chameleon> </div> i want directive response global scope's changes :
angular.module('app', []).directive('chameleon', function () { return { template: 'i {{ 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 need similar not-working code : * element.on('attributechange', function () { * scope.env = attrs.env * }); */ } }}); i know can use isolated scope bind values of surrounding scope, like
scope: { env: '=' } but need have independent component value of attribute env not going changed model.
feel free fork plunker.
you need use attrs.$observe work same $watch. works on {{}} value & change in value call $observe function.
code
attrs.$observe('env', function() { scope.color = getcolor(); });
Comments
Post a Comment