简体   繁体   English

Ionic,AngularJs:呈现视图后,指令属性$ watch停止工作

[英]Ionic, AngularJs: Directive attribute $watch stops working after view is rendered

I want to create an attribute directive for ionItem and I want it to watch its own value: 我想为ionItem创建一个属性指令,并且希望它观察自己的值:

<ion-item ng-repeat="item in items" my-dir="{{data.watchedValue}}">….</ion-item>

I have an issue with creating correct watch statement in the directive. 我在指令中创建正确的watch语句时遇到问题。 The watch is executed only once during initial view rendering. 在初始视图渲染期间,手表仅执行一次。 After that it is not invoked when data.watchedValue is changed. 此后,当data.watchedValue更改时,不会调用它。

Specific of the directive is that it is child of ionItem directive. 该指令的特定之处在于它是ionItem指令的ionItem

I have tried multiple approaches (see comments in my-dir source), but none of them works. 我尝试了多种方法(请参阅my-dir源中的注释),但是它们都不起作用。

Directive: 指示:

.directive('myDir', function() {
  return {
    restrict: 'A',
    require:  '^ionItem',
    link: function(scope, element, attr, itemCtrl) {
      console.log('my-dir initial value: ' + attr.myDir);

      if (angular.isDefined(attr.myDir)) {
        // scope.$watch("(" + attr.myDir + " === \"true\")", function(value) {
        // scope.$watch('!!(' + attr.myDir + ')', function(value) {
        scope.$watch(attr.myDir, function(value) {
          console.log('my-dir watch new value:  ' + value);
        });
      }

    } // link
  }; // return
}) // directive

Simplified directive usage: 简化的指令用法:

<button class="button" ng-click="data.watchedValue = !data.watchedValue">
  Change Value
</button>

<ion-content>
  <ion-list>
    <ion-item ng-repeat="item in items" my-dir="{{data.watchedValue}}">
      Item {{ item.id }}. Watched property: {{ data.watchedValue }}
    </ion-item>
  </ion-list>
</ion-content>

Code Pen with full example. 带有完整示例的代码笔 Press Change Value button to … change value. Change Value按钮以…更改值。

Watch the console for any logs after initial display. 初始显示后,请在控制台中查看任何日志。

You should be just passing scope variable name to directive attribute 您应该只将范围变量名称传递给指令attribute

<ion-item ng-repeat="item in items" my-dir="data.watchedValue">
  Item {{ item.id }}. Watched property: {{ data.watchedValue }}
</ion-item>

OR 要么

you could use attrs.$observe instead of $scope.$watch , which will basically keep an watch on {{}} interpolated value specified on attribute. 您可以使用attrs.$observe代替$scope.$watch ,这基本上可以监视属性上指定的{{}}插值。

If data.watchedValue has object then I'd highly recommend to go for 1st approach. 如果data.watchedValue有对象,那么我强烈建议您采用第一种方法。

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

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