1

我在指令和控制器之間有一個雙向綁定變量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發射?

回答

1

$watch是關注範圍內的屬性。如果你想觀看一個集合,你需要使用$watchCollection(用於淺看)或$watch('publish.selected_tags', function(newVal, oldVal){}, true)(用於深層觀看)。

相關問題