scope.$watch not working in angular directive

5k views Asked by At

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.

1

There are 1 answers

0
Jayantha Lal Sirisena On BEST ANSWER

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