为什么 AngularJS $scope.watch() 在我告诉它观察数组时停止工作?

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

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

HTML

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

Angular 指令:

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

Angular 控制器:

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()。阅读 here

试试这个

$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
    }
  }
);