angularjs - How to watch for a property change in a directive -
i have angular directive (with isolate scope) set this
<div ng="$last" somedirective datajson=mydata myprop="{{ mydata.myspecialprop }}"></div> (which gets rendered multiple times because it's inside ng-repeat.)
following instructions of so answer, tried observe myprop changes in directive, however, code inside $scope.watch never runs when property changes (on click event). tried scope.$watch(attrs.myprop, function(a,b){...)and never ran either. how watch change in myprop
myapp.directive('somedirective', function(){ return { restrict: 'ae', scope: { datajson: '=', myprop: '@ }, link: function(scope, elem, attrs){ scope.$watch(scope.myprop, function(a,b){ if (a != b){ console.log("doesn't called when not equal b"); }else{ } }); } }); } update: click event changes property handle in controller , i'm guessing isn't reflected in isolate scope directive $watch never getting triggered. there way handle that?
when use interpolation binding (@) cannot use scope.$watch, reserved two-way bindings (=) or internal scope properties.
instead, need use attrs.$observe similar job:
link: function(scope, elem, attrs){ attrs.$observe('myprop', function(newval, oldval) { // debug purposes console.log('new', newval, 'old', oldval); if (newval != oldval){ console.log("doesn't called when newval not equal oldval"); } else { // ... } }); } also, everytime myprop change, newval will different oldval, bit weird skip case 1 happen.
note: forgot doublequotes datajson two-way binding: datajson="mydata"
Comments
Post a Comment