Skip to content

Instantly share code, notes, and snippets.

@shanestillwell
Created December 24, 2012 20:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanestillwell/4370628 to your computer and use it in GitHub Desktop.
Save shanestillwell/4370628 to your computer and use it in GitHub Desktop.
AngularJS update model upon input blur
function Main() {}
// 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());
});
});
}
};
});
<input type="text" ng-model="value" ng-model-onblur>
{{value}}
@jonsamwell
Copy link

IE8 doesn't have the input event and will throw a mismatch error so use the $sniffer service to check prior to calling unbind.


if ($sniffer.hasEvent('input')) {
        elm.unbind('input');
      }

      elm.unbind('keydown').unbind('change');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment