为什么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>
角度指令:
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
}
}
);
相关文章:
- 如何在映射数组中添加换行符
- javascript结合了数组和字典
- 需要帮助设置json数组
- 不能从angular2中的子组件指定父组件中的数组
- 使用JS将数组转换为json对象
- 数组在递归方法中设置为null
- knockoutjs可观察数组
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 将数组从PHP传递到Javascript
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- 在函数中添加数组元素的数值
- 无法通过数组映射绑定
- javascript中的数组出错
- 如何使用 node.js 比较两个 json 数组
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 根据id将json数组组合为一个json数组
- 如何通过数组更新角度子范围
- 为什么AngularJS$scope.watch()在我告诉它监视数组时会停止工作
- 监视数组的子值
- Angular js 监视带有 ng-repeat 的 Select 标签上的对象数组