Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 436
Niclas Avatar asked Sep 16 '14 20:09

Niclas


People also ask

What is Ngchange?

Definition and UsageThe ng-change event is triggered at every change in the value. It will not wait until all changes are made, or when the input field loses focus. The ng-change event is only triggered if there is a actual change in the input value, and not if the change was made from a JavaScript.

How do I use $Watch in AngularJS?

The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.

How do you change the value of an NG model?

If we use two way binding syntax for ngModel the value will be updated. So the default (ngModelChange) function will update the value of ngModel property. i.e., user.Name . And the second (ngModelChange) will be triggered printing the user name value in the console.

What is Ngmodeloptions in Angular?

The ng-model-options directive is used to control the binding of an HTML form element and a variable in the scope. You can specify that the binding should wait for a specific event to occur, or wait a specific number of milliseconds, and more, see the legal values listed in the parameter values below.


1 Answers

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);
          });
        } 
      } ;
    }
);
like image 92
sylwester Avatar answered Sep 23 '22 16:09

sylwester