Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 960 of the free egghead.io lessons, plus get Angular 1.x content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Using ngModelOptions to Update on Blur

2:56 Angular 1.x lesson by

How do you change a text input from updating on every key stroke? With ngModelOptions it is really easy to control what event triggers the model update. In this lesson, we will modify a text input to update on blur instead of key up.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

How do you change a text input from updating on every key stroke? With ngModelOptions it is really easy to control what event triggers the model update. In this lesson, we will modify a text input to update on blur instead of key up.

In this lesson, we are going to use ngModelOptions to only update the model of a text field when a blur event has happened, instead of updating it on every single keystroke.

A common scenario is when I'm working with a team of developers. Somebody comes up and asks me, "I want to update the model only after the user has left the text field and not on every single keystroke. That's simply too much. We need to dial it back."

With ngModelOptions, it is really, really easy to accomplish that. Let's hop into the code and see what we have here, real quick. We have a main controller as main. Then we have a main message that's bound to an input field. Then, in another div here, we have main.output.

If we hop into the JavaScript, you can see here that we have main.message, main.output, and then we have a watch expression where we are watching main.message. When main.message is changed or modified, then it changes main.output to message updated with the new value.

Currently, when I type this, it immediately updates with every single keystroke. What we want to do is force that to only update when the user has removed focus from the text field, essentially the blur effect.

We'll hop back into the code. Using ng-model-options, we will pass in the model options object and say "updateOn." We'll set that to blur. Let's save the file and see this in action.

When I start typing, you can see it's no longer updating until I click out of the text field and it triggers that watch expression. Let me just take this off. You can see that it's updating every single time. Let me just put this back on. I tab out, and it is updated.

I also recommend checking out Kent Dodd's excellent series on ngModelOptions and the incredibly powerful things that you can do. I am covering just a specific scenario, but he really gets into detail about the amazing things you can do with this new feature on ngModel. This is just one tool in your toolbox. I look forward to seeing you in additional lessons.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?