简体   繁体   中英

scope.$watch not working in angular directive

I have made a custom directive and used ng-model, but when the model updates, the directive not even though i'm watching the event. Here's the code:

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
        };
    }
}}]);

and the view:

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

Whenever new values are added to a products recentPriceHistory, the view doesnt get updated.

By default when comparing an old value with new value angular will be checked for "reference" equality. But if you need to check for the value then you need to do like this,

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

But the problem here is that angular will deep watch all the properties of the ngModel for changes, If the ngModel variable is a complex object it wilt affects the performance. What you can do it to avoid this is to check only for one property,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM