Angularjs: Listen to model change in a directive

All we need is an easy explanation of the problem, so here it is.

I’m trying to find out how I can listen to when the model is updated within an directive.

eventEditor.directive('myAmount',function(){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
          scope.$watch(attr['ngModel'], function (v) {
            console.log('value changed, new value is: ' + v);
          });
        } 
      } 
    }
};

});

The directive is called within ng-repeat as

<div ng-repeat="ticket in tickets">
    <input my-amount ng-model="ticket.price"></input> 
</div>

Very happy for any help. I don’t understand how the scope attribute looks like within an ng-repeat.

Thanks.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

http://jsbin.com/mihupo/1/edit

attrs instead attr

app.directive('myAmount',function(){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
          scope.$watch(attrs['ngModel'], function (v) {
            console.log('value changed, new value is: ' + v);
          });
        } 
      } ;
    }
);

Method 2

Try doing this

eventEditor.directive('myAmount',function(){
    return {
    restrict: 'A',
    scope: {model: '=ngModel'},
    link: function(scope, elem, attrs) {
            scope.$watch('model', function (v) {
            console.log('value changed, new value is: ' + v);
          });
        } 
      } 
    }
  };
});

Method 3

eventEditor.directive('myAmount',function(){
return {
    restrict: 'A',
    required : 'ngModel'       // Add required property 
    link: function(scope, elem, attrs,ngModelCtr) {

      ngModelCtr.$render = function(){   //  Add $render 
      // Your logic
    }

  } 
 }
 };
 });
  1. Add a required property with ngModel, Since you are using ngModel (i mean actual angular ng-model, not the user custom ng-model attribute).
  2. Then call $render function. It will execute as soon as there is a change in ngModel (change in values of $modelValue and $viewValue).
    https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$render

You can use $watch that is also correct.

Method 4

Following code works for me.

app.directive('myAmount',function(){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
          attrs.$observe('ngModel', function (v) {
            console.log('value changed, new value is: ' + v);
          });
        } 
      } ;
    }
);

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply