Search code examples
javascriptangularjsangularjs-directiveangularjs-watch

$watch in controller not firing on pushing items into array in directive


I have a two-way binded variable publish.selected_tags between a directive and a controller.

I have kept a $watch on that variable in my controller:

$scope.$watch('publish.selected_tags', function(new_val, old_val) {
    console.log(new_val); //print new value
})

The problem I am facing is that when I push an item into the selected_tags list, the $watch is not fired:

return {
    scope: {
        selected_tags: '='
    },
    link: function(scope, element, attrs) {
        scope.selected_tags.push('item') //watch in the controller not getting fired
    }
}

However, when I assign selected_tags to an array the $watch in the controller gets fired:

return {
    scope: {
        selected_tags: '='
    },
    link: function(scope, element, attrs) {
        scope.selected_tags = ['item'] //watch in the controller getting fired!
    }
}

Why is this happening? How can I get my $watch to fire in the case where I want to push an element?


Solution

  • Use $scope.$watchCollection(...)

    Ref. https://docs.angularjs.org/api/ng/type/$rootScope.Scope