【问题标题】:Why does AngularJS $scope.watch() stop working when I tell it to watch an Array?当我告诉 AngularJS $scope.watch() 监视数组时,为什么它会停止工作?
【发布时间】:2023-03-31 00:36:01
【问题描述】:

我有一个 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 而不是单个值并传递最后一个参数 @987654327 来做到这一点@给它。现在(作为临时步骤)我调整了我的控制器以获取一个包含一个值的数组,看看这是否可行。我的控制器现在看起来像这样:

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)

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

【问题讨论】:

    标签: javascript angularjs d3.js angularjs-scope watch


    【解决方案1】:

    对于数组,您必须使用$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
        }
      }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多