为什么AngularJS$scope.watch()在我告诉它监视数组时会停止工作

Why does AngularJS $scope.watch() stop working when I tell it to watch an Array?

本文关键字:监视 数组 停止工作 scope AngularJS watch 为什么      更新时间:2023-09-26

我有一个AngularJS应用程序,我在其中创建了一个指令myp-my-directive,该指令基于属性my-attribute在屏幕上绘制图表。我就是这样做的。它起作用:

HTML

<myp-my-directive my-attribute="[1, 2, 3]">
</myp-my-directive>

角度指令:

myapp.directive('mypMyDirective',function() {
    return {
      restrict:'E',
      scope: {
        myAttribute: '='
      },
      controller: 'StuffCtrl',
      controllerAs: 'stuffCtrl',
      bindToController: true,
      templateUrl: 'myHtml.html'
    };
  }
);

角度控制器:

myapp.controller('StuffCtrl', function($scope) {
    var self = this;
    $scope.$watch(function() {return self.myAttribute;}, function (objVal)
      {
        if (!(typeof objVal === "object" && objVal.length > 0)) {
          var myObject = Object.assign({}, objVal.data);
          // Draw a fancy chart based using d3.js based on myObject
        }
      }
    );
  }
);

以上工作。

但我刚刚意识到,我需要根据2个属性绘制图表,而不仅仅是1个。我知道我可以通过向$scope.$watch返回一个数组而不是单个值,并向其传递最后一个参数true来实现这一点。目前(作为临时步骤),我调整了我的控制器,使其采用包含一个值的数组,看看这是否可行。我的控制器现在看起来是这样的:

myapp.controller('StuffCtrl', function($scope) {
    var self = this;
    $scope.$watch(function() {return [self.myAttribute];}, function (objVal)
      {
        if (!(typeof objVal[0] === "object" && objVal[0].length > 0)) {
          var myObject = Object.assign({}, objVal[0].data);
          // Draw a fancy chart based using d3.js based on myObject
        }
      }
    );
  }, true
);

但这会产生以下错误:

angular.js:13236 RangeError: Maximum call stack size exceeded
    at equals (angular.js:1048)
    at equals (angular.js:1058)
    at equals (angular.js:1074)
    at equals (angular.js:1058)
    at equals (angular.js:1074)
    at equals (angular.js:1058)
    at equals (angular.js:1074)
    at equals (angular.js:1058)
    at equals (angular.js:1074)
    at equals (angular.js:1058)

为什么?我的控制器的两个版本不应该是等效的吗?为什么一个有效,另一个失败?从指令向控制器发送第二个属性的最佳方式是什么?

对于一个数组,您必须使用$scope.$watchCollection()。阅读此处

试试这个

$scope.$watchCollection(function() {return [self.myAttribute];}, function (newVal, oldVal)
  {
    if (!(typeof newVal[0] === "object" && newVal[0].length > 0)) {
      var myObject = Object.assign({}, newVal[0].data);
      // Draw a fancy chart based using d3.js based on myObject
    }
  }
);