I'm trying to create a custom directive that provides similar change notification as the input control. With input controls, you can do the following:
<input type="text" ng-model="foo" ng-change="bar(a,b)">
In this case, the bar function specified with ng-change will only be called once every time the value of foo is changed. I created a custom directive and I want to add the same type of change notification.
<div my-directive ng-model="foo" ng-change="bar(a,b)"></div>
I first tried to include the change handler in the scope and then execute it, but including it in the scope causes it to be called 12 times when it is instantiated and 12 times when it changes because I believe that is how often the attribute is being evaluated.
return {
templateUrl: '...',
restrict: 'A',
require: '^ngModel',
scope: {
ngModel: '=',
ngChange: '='
},
link: function postLink(scope, element, attrs) {
if(angular.isFunction(scope.ngChange) {
scope.ngChange(); // bar is called 12 times
}
}
}
Then I looked at the Angular source code and saw that they eval the value of the attribute for the change handler on input. I tried to do that, but the specified function never seems to get called.
return {
templateUrl: '...',
restrict: 'A',
require: '^ngModel',
scope: {
ngModel: '='
},
link: function postLink(scope, element, attrs) {
scope.$eval(attrs.ngChange); // bar is never called
}
}
What would be the right way to do this?