簡體   English   中英

范圍。$ 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時,視圖都不會更新。

默認情況下,將舊值與新值進行比較時,將檢查“參考”相等性。 但如果你需要檢查價值,那么你需要這樣做,

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

但是這里的問題是angular會深入監視ngModel的所有屬性以進行更改。如果ngModel變量是一個復雜的對象,它將影響性能。 你可以做到這一點來避免這種情況只檢查一個屬性,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM