Created
February 20, 2013 05:13
-
-
Save boneskull/4993082 to your computer and use it in GitHub Desktop.
redefine certain directives to update model on blur instead of keydown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*global angular*/ | |
/** | |
* Include this module if you want text boxes to update on blur instead of on keydown/input/change. | |
*/ | |
(function () { | |
'use strict'; | |
var blur = angular.module('decBlurModel', []); | |
/** | |
* Overrides the 'input' directive to update on blur instead of keydown. | |
* For this view we want to save the campaign whenever somebody blurs | |
* out of an input or whatever. Otherwise we'd be hitting the server | |
* every keystroke. | |
*/ | |
var directive = ['$parse', function ($parse) { | |
return { | |
restrict: 'E', | |
require: '?ngModel', | |
link: function (scope, elm, attr, ngModel) { | |
var model; | |
if (!ngModel) { | |
return; | |
} | |
elm.off('input').off('keydown').off('change'); | |
elm.on('blur', function () { | |
scope.$apply(function () { | |
ngModel.$setViewValue(elm.val()); | |
}); | |
}); | |
// if we have a case where we want to actually use this keydown stuff while this directive is in use | |
// we need to find away around it. we can supply a model to update on every keydown that is not the | |
// default ng-model, then get our value from that when appropriate. | |
if (attr.updateOnKeydown) { | |
model = $parse(attr.updateOnKeydown); | |
elm.on('input keydown change', function () { | |
scope.$apply(function () { | |
model.assign(scope, elm.val()); | |
}); | |
}); | |
} | |
} | |
}; | |
}]; | |
blur.directive('input', directive); | |
blur.directive('textarea', directive); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment