$watch'ing for data changes in an Angular directive

前端 未结 3 1990
春和景丽
春和景丽 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:17

    My version for a directive that uses jqplot to plot the data once it becomes available:

        app.directive('lineChart', function() {
            $.jqplot.config.enablePlugins = true;
    
            return function(scope, element, attrs) {
                scope.$watch(attrs.lineChart, function(newValue, oldValue) {
                    if (newValue) {
                        // alert(scope.$eval(attrs.lineChart));
                        var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
                    }
                });
            }
    });
    
    0 讨论(0)
  • 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) {});
    
    0 讨论(0)
  • 2020-11-29 16:34

    Because if you want to trigger your data with deep of it,you have to pass 3th argument true of your listener.By default it's false and it meens that you function will trigger,only when your variable will change not it's field.

    0 讨论(0)
提交回复
热议问题