Niclas
Niclas

Reputation: 1406

Angularjs: Listen to model change in a directive

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.

Upvotes: 16

Views: 22136

Answers (4)

AnshulJS
AnshulJS

Reputation: 328

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.

Upvotes: 4

Susobhan Das
Susobhan Das

Reputation: 133

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

Upvotes: -2

az7ar
az7ar

Reputation: 5237

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

Upvotes: 6

sylwester
sylwester

Reputation: 16498

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

Upvotes: 22

Related Questions