控制器中的 $watch 不会触发将项目推入指令中的数组

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

我在指令和控制器之间有一个双向绑定变量publish.selected_tags

我在我的控制器中为该变量保留了一个 $watch

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

我面临的问题是 当我将一个项目推selected_tags 列表时,$watch 没有被触发:

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

但是,当我将 selected_tags 分配给数组时,控制器中的 $watch 被触发:

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

为什么会这样?如果我想推送一个元素,我怎样才能让我的 $watch 触发?

使用 $scope.$watchCollection(...)

参考。 https://docs.angularjs.org/api/ng/type/$rootScope.Scope

$watch 用于监视范围内的属性。如果你想看一个集合,你需要使用$watchCollection(对于浅层观察)或$watch('publish.selected_tags', function(newVal, oldVal){}, true)(对于深度观察)。

我认为您应该使用 $watchCollection() 来观察数组中的变化。 $watch() 当表达式的值发生变化时触发,而不是 属性 如果我没记错的话你正在观察的对象内部发生变化。

https://code.angularjs.org/1.1.4/docs/api/ng.$rootScope.Scope#$watchCollection