Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Blur + Changed?

Tags:

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 ?

like image 932
Roger Johansson Avatar asked Dec 07 '13 13:12

Roger Johansson


2 Answers

Use ng-model options. Like this, ng-change will only trigger when the input is blurred.

<input type="text" 
       ng-model="a.b" 
       ng-model-options="{updateOn: 'blur'}" 
       ng-change="onchange()"/>
like image 154
Niels Steenbeek Avatar answered Sep 24 '22 09:09

Niels Steenbeek


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()" />
like image 43
Roger Johansson Avatar answered Sep 23 '22 09:09

Roger Johansson