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 833 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.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.

Using ngModel in Custom Directives

1:42 Angular 1.x lesson by

You can use ngModel in your own directives, but there are a few things you'll need to do to get it working properly.

Get the Code Now
click to level up

egghead.io comment guidelines


You can use ngModel in your own directives, but there are a few things you'll need to do to get it working properly.


Thank you for introducing ngModelController. Would you please continue down this path in future videos? I am very interested in using ngModelController for custom input directives, but have found the API very difficult to grok. Thanks!

In reply to egghead.io

Hey Andy, this is the first in a series on reusable directives!

In reply to Andy

Nice. Hope there is more coming on ngModel custom use.

You can use ngModel in your own custom directives. It just requires a bit of knowledge about requiring other directives, controllers, and using their APIs.

So what this looks like is we're going to require ngModel because this is a directive. Ngmodel is the directive that sits along side our bank directive.

Then, when we build our link function, we want to make sure to include that fourth parameter meaning that this is the controller that ngModel gives us to interact with.

I'm going to name this, "ngModel," just to make it more clear. So what I'm going to do here, I'm going to say, "element on click," and then when I click, I'm going to say, "ngModel set view value to ngModel.view value plus 10."

So it's going to add 10 every time I click on it. Then, when that's done, I'll just say, "scope, apply."

So, you can see when I refresh over here and any time I can click on this, this is going to go up $10 each time because I'm adding $10 to the current view value using set view value.

So basically what this means is that the ngModel controller, which is this controller, has a few methods on it such as set view value. Has some properties such as view value and then once we make those changes, we need to apply ourselves so that we tell it explicitly what we're done with our changes and how and when that should update the scope.

Joel's Head
Why are we asking?