Within my code, I have established a two-way binding variable called publish.selected_tags
that connects a directive with a controller.
To monitor changes in this variable, I implemented a $watch
function within my controller:
$scope.$watch('publish.selected_tags', function(new_val, old_val) {
console.log(new_val); //print new value
})
A dilemma has arisen where the triggering of the $watch does not occur when an item is added to the selected_tags
array:
return {
scope: {
selected_tags: '='
},
link: function(scope, element, attrs) {
scope.selected_tags.push('item') //controller's watch remains inactive
}
}
Remarkably, however, once the selected_tags
is assigned as an array, the controller's $watch
functions correctly:
return {
scope: {
selected_tags: '='
},
link: function(scope, element, attrs) {
scope.selected_tags = ['item'] //controller's watch successfully triggered!
}
}
This inconsistency raises questions. Why does the $watch
not activate when pushing elements? How can this be resolved?