Reputation: 13943
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
<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.
Anyway after pressing the shortcut the $watch
is not triggered whereas the array is updated
I can't find the error in my code
Upvotes: 0
Views: 36
Reputation: 26828
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
:
$scope.$watchCollection("observation",
$watchCollection
also monitors the content of the array, i.e. it checks if something was removed or added.
Upvotes: 2