Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  42] [ 5]  / answers: 1 / hits: 23069  / 11 Years ago, sat, december 7, 2013, 12:00:00

What is the easiest way to combine ng-changed and ng-blur?



I've found this post: How to let ng-model not update immediately?



However, this does no longer work in angluar 1.2+
Is there any way to achieve the same behavior?



I guess I have to store a copy of the old value myself and compare the new value to that on blur if I try to do the same, or is there any easier way ?


More From » angularjs

 Answers
1

This does what I want.
It stores the value on focus, and compares it to the new value on blur, if changed, it triggers the expression in the attribute.



 app.directive('changeOnBlur', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ngModelCtrl) {
if (attrs.type === 'radio' || attrs.type === 'checkbox')
return;

var expressionToCall = attrs.changeOnBlur;

var oldValue = null;
elm.bind('focus',function() {
scope.$apply(function() {
oldValue = elm.val();
console.log(oldValue);
});
})
elm.bind('blur', function() {
scope.$apply(function() {
var newValue = elm.val();
console.log(newValue);
if (newValue !== oldValue){
scope.$eval(expressionToCall);
}
//alert('changed ' + oldValue);
});
});
}
};
});


usage:



 <input ng-model=foo change-on-blur=someFunc() />

[#73863] Thursday, December 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jennifer

Total Points: 517
Total Questions: 110
Total Answers: 104

Location: New Caledonia
Member since Fri, Sep 11, 2020
4 Years ago
;