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

scope.$watch not working in angular directive

我已经制作了一个自定义指令并使用了 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>

每当将新值添加到产品 recentPriceHistory 时,视图都不会更新。

默认情况下,比较旧值和新值时 angular 将检查 "reference" 是否相等。但是如果你需要检查值那么你需要这样做,

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

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

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