$watch'ing for data changes in an Angular directive

前端 未结 3 1992
春和景丽
春和景丽 2020-11-29 15:40

How can I trigger a $watch variable in an Angular directive when manipulating the data inside (e.g., inserting or removing data), but not assign a new object to

3条回答
  •  清酒与你
    2020-11-29 16:34

    You need to enable deep object dirty checking. By default angular only checks the reference of the top level variable that you watch.

    App.directive('d3Visualization', function() {
        return {
            restrict: 'E',
            scope: {
                val: '='
            },
            link: function(scope, element, attrs) {
                scope.$watch('val', function(newValue, oldValue) {
                    if (newValue)
                        console.log("I see a data change!");
                }, true);
            }
        }
    });
    

    see Scope. The third parameter of the $watch function enables deep dirty checking if it's set to true.

    Take note that deep dirty checking is expensive. So if you just need to watch the children array instead of the whole data variable the watch the variable directly.

    scope.$watch('val.children', function(newValue, oldValue) {}, true);
    

    version 1.2.x introduced $watchCollection

    Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)

    scope.$watchCollection('val.children', function(newValue, oldValue) {});
    

提交回复
热议问题