ngModelBur Directive

by langdonx

HTML

<div ng-app="TestApp" ng-controller="TestCtrl">
    <span>{{item.name}}</span>
    <input type="text" ng-model-blur="item.name" />
    <div>type something into the box and click here to fire the blur event</div>
</div>

JavaScript

var app = angular.module('TestApp', []);

app.controller('TestCtrl', function ($scope) {
    $scope.item = {
        name: 'test'
    };
});

app.directive('ngModelBlur', function ($parse) {
    return {
        restrict: 'A',
        scope: {
            ngModelBlur: '='
        },
        link: function (scope, element, attrs) {
            // set the initial value of the textbox
            element.val(scope.ngModelBlur);

            // on blur, update the value in scope
            element.bind('blur', function (blurEvent) {
                scope.$apply(function () {
                    scope.ngModelBlur = element.val();
                });
            })
        }
    };
});