Weedoze Weedoze - 1 year ago 72
AngularJS Question

Watch directive scope not working


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.


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('linechart', [function() {
return {
restrict: 'E',
scope: {
id: "@",
observation: "="
link: function($scope, element, attrs) {
$scope.$watch("observation", function(newVal, oldVal){
console.log("OBS : " + newVal);
}, true);


<linechart id="linechart3" observation="vm.observation"></linechart>

When the page load the chart correctly display the data and the console correctly log inside
is correctly executed.

Anyway after pressing the shortcut the
is not triggered whereas the array is updated

I can't find the error in my code

Answer Source

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:


$watchCollection also monitors the content of the array, i.e. it checks if something was removed or added.