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 ?
Advertisement
Answer
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.
JavaScript
x
31
31
1
app.directive('changeOnBlur', function() {
2
return {
3
restrict: 'A',
4
require: 'ngModel',
5
link: function(scope, elm, attrs, ngModelCtrl) {
6
if (attrs.type === 'radio' || attrs.type === 'checkbox')
7
return;
8
9
var expressionToCall = attrs.changeOnBlur;
10
11
var oldValue = null;
12
elm.bind('focus',function() {
13
scope.$apply(function() {
14
oldValue = elm.val();
15
console.log(oldValue);
16
});
17
})
18
elm.bind('blur', function() {
19
scope.$apply(function() {
20
var newValue = elm.val();
21
console.log(newValue);
22
if (newValue !== oldValue){
23
scope.$eval(expressionToCall);
24
}
25
//alert('changed ' + oldValue);
26
});
27
});
28
}
29
};
30
});
31
usage:
JavaScript
1
2
1
<input ng-model="foo" change-on-blur="someFunc()" />
2