Scope. $ watch doesn't work in angular directive.

I created a custom directive and used ng-model, but when the model is updated, the directive doesn't even look at 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 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>

      

When new values ​​are added to recentPriceHistory, the view is not updated.

+3


source to share


1 answer


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

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

      



But the problem is that angular will deeply monitor all ngModel properties for changes. If the variable ngModel

is a complex object, it affects performance. What can you do to avoid this, only one property needs to be checked,

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

      

+7


source







All Articles