AngularJS Example

by sundaramkumar

HTML

<script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
<div ng-app="MyApp">
    <div ng-controller="MyController">
    <form>
        <input ng-model="name" update-on-blur></input><br/>
        <textarea ng-model="description" update-on-blur></textarea>
    </form>
        <p>Name:<br/><pre>{{name}}</pre></p>
        <p>Description: <pre>{{description}}</pre></p>
    </div>
</div>

JavaScript

var myApp = angular.module('MyApp',[])
myApp.directive('updateOnBlur', function() {
    return {
        restrict: 'EA',
        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());
                });
            });
        }
    };
});

myApp.controller('MyController', function($scope) {
    $scope.name = "Enter name";
    $scope.description = "Enter description"
});