简体   繁体   English

如何观察指令中的属性变化

[英]How to watch for a property change in a directive

I have an angular directive (with isolate scope) set up like this我有一个像这样设置的角度指令(带有隔离范围)

<div ng="$last" somedirective datajson=mydata myprop="{{ mydata.myspecialprop }}"></div>

(which actually gets rendered multiple times because it's inside an ng-repeat.) (实际上会多次渲染,因为它在 ng-repeat 中。)

Following the instructions of this SO answer , I tried to observe myprop for changes in the directive, however, the code inside the $scope.watch never runs even when the property changes (on a click event).按照这个SO answer的说明,我尝试观察myprop指令中的更改,但是,即使属性更改(在单击事件上), $scope.watch 中的代码也永远不会运行。 I also tried scope.$watch(attrs.myprop, function(a,b){...) and it never ran either.我也试过scope.$watch(attrs.myprop, function(a,b){...)并且它也从未运行过。 How do I watch for the change in myprop我如何观察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 get called when a not equal b");
        } else {

        }
      });
    }
  };
}

Update: the click event that changes the property is handle in the controller and I'm guessing this isn't reflected back in the isolate scope directive so that $watch is never getting triggered.更新:更改属性的点击事件是控制器中的句柄,我猜这不会反映在隔离范围指令中,因此永远不会触发 $watch 。 Is there a way to handle that?有办法处理吗?

When you use an interpolation binding ( @ ) you cannot use scope.$watch , which is reserved for two-way bindings ( = ) or internal scope properties.当您使用插值绑定 ( @ ) 时,您不能使用scope.$watch ,它是为双向绑定 ( = ) 或内部作用域属性保留的。

Instead, you need to use attrs.$observe which does a similar job:相反,您需要使用attrs.$observe来完成类似的工作:

link: function(scope, elem, attrs){
   attrs.$observe('myprop', function(newVal, oldVal) {
     // For debug purposes
     console.log('new', newVal, 'old', oldVal);
     if (newVal != oldVal){
          console.log("doesn't get called when newVal not equal oldVal");
      } else {
          // ...
     } 
   });
 }

Also, everytime myprop change, the newVal will be different from its oldVal , so it is a bit weird that you skip that case which is the only one which will happen.此外,每次myprop更改时, newVal都会与其oldVal不同,因此您跳过这种情况oldVal ,这是唯一会发生的情况。

NOTE: you also forgot doublequotes for the datajson two-way binding: datajson="mydata"注意:您还忘记了datajson双向绑定的双引号: datajson="mydata"

Intead of passing a string, try it as variable Intead 传递字符串,尝试将其作为变量

scope: {
     datajson: '=',
     myprop: '=' //change to equal so you can watch it (it has more sense i think)
  }

then change html, removing braces from mydata.myspecialprop然后更改 html,从 mydata.myspecialprop 中删除大括号

<div ng="$last" somedirective datajson="mydata" myprop="mydata.myspecialprop"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM