Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let ng-model not update immediately?

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?

like image 613
Freewind Avatar asked Feb 06 '13 06:02

Freewind


People also ask

What triggers ngModelChange?

ngModelChange It fires when the model changes. You cannot use this event without ngModel directive. change triggers when the user changes the input. ngModelChange triggers when the model changes, irrespective of that change is caused by the user or not.

Can I use ngModelChange without ngModel?

The NgModel class has the update property with an EventEmitter instance bound to it. This means we can't use (ngModelChange) without ngModel .

How do you use Ngmodeloptions?

The ng-model-options directive is used to control the binding of an HTML form element and a variable in the scope. You can specify that the binding should wait for a specific event to occur, or wait a specific number of milliseconds, and more, see the legal values listed in the parameter values below.

What is the difference between ngModel and [( ngModel )]?

The answer is: (ngModel) causes a 1-way data-binding, whereas [(ngModel)] ensures a two-way data binding.


2 Answers

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 } }" 

NgModelOptions docs

Example:

<input type="text" name="username"        ng-model="user.name"        ng-model-options="{updateOn: 'default blur', debounce: {default: 500, blur: 0} }" /> 
like image 89
manikanta Avatar answered Sep 22 '22 15:09

manikanta


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.

like image 26
Martin Avatar answered Sep 19 '22 15:09

Martin