scope.$watch 在角度指令中不起作用

Posted

技术标签:

【中文标题】scope.$watch 在角度指令中不起作用【英文标题】:scope.$watch not working in angular directive 【发布时间】:2015-08-31 23:47:26 【问题描述】:

我已经制作了一个自定义指令并使用了 ng-model,但是当模型更新时,即使我正在观看事件,该指令也没有。代码如下:

angular.module('Directives').directive("customDirective", ['$window', function ($window) 

return 
    restrict: "E",
    require: 'ngModel',
    scope: 
        ngModel: '=',
    ,
    link: function (scope, elem, attrs, ngModel) 

        // IF the model changes, re-render
        scope.$watch('ngModel', function (newVal, oldVal) 
            render();
        );

        // We want to re-render in case of resize
        angular.element($window).bind('resize', function () 
            //this does work
            render();
        )

        var render = function () 
            //doing some work here
        ;
    
]);

和视图:

<div ng-repeat="product in pageCtrl.productList track by product.id">
<h3> product.name </h3>
<custom-directive ng-model="product.recentPriceHistory">
    &nbsp;
</custom-directive>

每当向产品最近价格历史记录添加新值时,视图都不会更新。

【问题讨论】:

【参考方案1】:

默认情况下,将旧值与新值进行比较时,将检查“参考”是否相等。但是如果您需要检查该值,那么您需要这样做,

scope.$watch('ngModel', function (newVal, oldVal) 
    render();
, true);

但是这里的问题是 Angular 会深入观察 ngModel 的所有属性的变化,如果 ngModel 变量是一个复杂的对象,它会影响性能。为了避免这种情况,您可以做的就是只检查一个属性,

scope.$watch('ngModel.someProperty', function (newVal, oldVal) 
    render();
, true);

【讨论】:

以上是关于scope.$watch 在角度指令中不起作用的主要内容,如果未能解决你的问题,请参考以下文章