Reputation: 198318
Code:
<input type="text" ng-modal="name" />
{{name}}
When I input something into the input
, the following {{name}}
will change immediately. Is it able to configure it only update the name
after I input all characters and leave the input?
Upvotes: 22
Views: 29146
Reputation: 8866
Update
As many have mentioned Angular now has built-in support for this using the ng-model-options
directive. See more here.
<input type="text" ng-model="name" ng-model-options="{updateOn: 'blur'}" />
Old answer below:
There's no built-in option for ng-model to change that behaviour, but you can write a custom directive doing it. @Gloopy wrote a directive like that for another question. You can look at the fiddle here.
The directive unregisters from the input
and keydown
events which trigger the update after each keystroke.
<input type="text" ng-model="name" ng-model-onblur />
Update:
Updated fiddle to use latest stable AngularJS (1.2.16 as of writing), instead of directly referencing the master version at github.
Also added an explicit priority so that the directive is run after ng-model
to ensure event listeners are changed correctly.
Upvotes: 22
Reputation: 4834
A better option is to use the ng-model-options:
<input type="text" ng-model="name" ng-model-options="{updateOn: 'blur'}" />
Upvotes: 9
Reputation: 2464
Working directive code(ng-1.2RC3):
use:
ng-model-onblur
.directive('ngModelOnblur', function () {
return {
restrict: 'A',
require: 'ngModel',
priority: 1,
link: function (scope, element, attrs, ngModelCtrl) {
if (attrs.type === 'radio' || attrs.type === 'checkbox') { return; }
var update = function () {
scope.$apply(function () {
ngModelCtrl.$setViewValue(element.val().trim());
ngModelCtrl.$render();
});
};
element.off('input').off('keydown').off('change').on('focus', function () {
scope.$apply(function () {
ngModelCtrl.$setPristine();
});
}).on('blur', update).on('keydown', function (e) {
if (e.keyCode === 13) {
update();
}
});
}
};
})
Upvotes: 5
Reputation: 8500
This is about recent additions to AngularJS, to serve as future answer.
Angular newer versions (now in 1.3 beta), AngularJS natively supports this option, using ngModelOptions
, like
ng-model-options="{ updateOn: 'default blur', debounce: { default: 500, blur: 0 } }"
Example:
<input type="text" name="username"
ng-model="user.name"
ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0} }" />
Upvotes: 53