[英]Watch directive scope not working
Context 语境
My controller stores an array. 我的控制器存储一个数组。 When pressing a specific shortcut on the keyboard I add a new object to this array.
当按下键盘上的特定快捷方式时,我向该数组添加了一个新对象。
The array is used inside a directive to display a chart. 该数组用于指令内部以显示图表。
So, on shortcut pressed the chart should be updated with the new value. 因此,按下快捷键后,图表应使用新值进行更新。
Controller 控制者
vm.observation = [{
"sale": "202",
"year": "2010"
}, {
"sale": "215",
"year": "2011"
}, {
"sale": "179",
"year": "2012"
}, {
"sale": "199",
"year": "2013"
}, {
"sale": "134",
"year": "2014"
}, {
"sale": "176",
"year": "2015"
}];
Directive 指示
angular.module('spwApp.directives')
.directive('linechart', [function() {
return {
restrict: 'E',
scope: {
id: "@",
observation: "="
},
link: function($scope, element, attrs) {
$scope.$watch("observation", function(newVal, oldVal){
console.log("OBS : " + newVal);
}, true);
}
}
}])
HTML 的HTML
<linechart id="linechart3" observation="vm.observation"></linechart>
When the page load the chart correctly display the data and the console correctly log inside $watch
is correctly executed. 页面加载后,图表将正确显示数据,并且控制台将正确执行
$watch
日志。
Anyway after pressing the shortcut the $watch
is not triggered whereas the array is updated 无论如何,按下快捷键后,不会触发
$watch
而数组会更新
I can't find the error in my code 我在代码中找不到错误
You add something to the array, but the array itself stays the same. 您向数组添加了一些内容,但数组本身保持不变。 A regular watcher only reacts to a value that changes.
常规观察者仅对变化的值做出反应。 That's why Angular also provides
$watchCollection
: 这就是Angular还提供
$watchCollection
的原因:
$scope.$watchCollection("observation",
$watchCollection
also monitors the content of the array, ie it checks if something was removed or added. $watchCollection
还监视数组的内容,即检查是否已删除或添加了某些内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.