angularjs onblur directive

Thanks to http://stackoverflow.com/users/1207991/gloopy

by michaeldausmann

HTML

<script src="http://ci.angularjs.org/job/angular.js-angular-master/ws/build/angular.js"></script>
<div ng-app='app' ng-controller='Main'>
    <input type="text" ng-model="name" ng-model-onblur ng-change="update()"></input>
    <input type="text" ng-model="address " ng-model-onblur ng-change="update()"></input>
    <hr/>
    name: {{name }}
    address: {{address}}
</div>

JavaScript

function Main($scope) 
{
    $scope.name = 'Bob';
    $scope.address = "Crazy Town";
    
    $scope.update = function(){
        //You can put stuff here if you want to respond explicity to the model change.
    }
}


// override the default input to update on blur
angular.module('app', []).directive('ngModelOnblur', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elm, attr, ngModelCtrl) {
            if (attr.type === 'radio' || attr.type === 'checkbox') return;
            
            elm.unbind('input').unbind('keydown').unbind('change');
            elm.bind('blur', function() {
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(elm.val());
                });         
            });
        }
    };
});