Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 控制器中的$watch在指令中将项目推入数组时未触发_Javascript_Angularjs_Angularjs Directive_Angularjs Watch - Fatal编程技术网

Javascript 控制器中的$watch在指令中将项目推入数组时未触发

Javascript 控制器中的$watch在指令中将项目推入数组时未触发,javascript,angularjs,angularjs-directive,angularjs-watch,Javascript,Angularjs,Angularjs Directive,Angularjs Watch,我有一个双向绑定变量publish.selected_标签,位于指令和控制器之间 我在控制器中的该变量上保留了一个$watch: $scope.$watch('publish.selected_tags', function(new_val, old_val) { console.log(new_val); //print new value }) 我面临的问题是,当我将一个项目推入所选标签列表时,$watch不会被触发: return { scope: { s

我有一个双向绑定变量
publish.selected_标签
,位于指令和控制器之间

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

$scope.$watch('publish.selected_tags', function(new_val, old_val) {
    console.log(new_val); //print new value
})
我面临的问题是,当我将一个项目推入
所选标签列表时,
$watch
不会被触发:

return {
    scope: {
        selected_tags: '='
    },
    link: function(scope, element, attrs) {
        scope.selected_tags.push('item') //watch in the controller not getting fired
    }
}
但是,当我将
选定的_标记
分配给数组时,控制器中的
$watch
将被触发:

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

为什么会这样?如果我想推动一个元素,如何让我的
$watch
启动

使用$scope.$watchCollection(…)


参考

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

我认为你应该使用
$watchCollection()
来观察数组中的变化
$watch()
在表达式的值更改时激发,如果我没有弄错的话,则不会在正在监视的对象内部的属性更改时激发