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 832 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 the ngChange Directive in Angular

2:25 Angular 1.x lesson by

The ngChange directive will allow you to monitor value changes on input elements in your AngularJS applications

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

The ngChange directive will allow you to monitor value changes on input elements in your AngularJS applications

Avatar
Bharat

Hello Ben,
Thanks for putting this together. It clarifies the difference between $watch and ngchange very well.
Regards,
Bharat

In reply to egghead.io

Previously we looked at how to use the scope.watch method to monitor a value. We're watching the user.password property. When that changes we're going to pass that to this checkPassword function. CheckPassword is going to check it against our requirements of a specific length of at least four and make sure that there's numbers in it.

We can see that if we run this and start typing here it's telling us that it's too short, must include numbers. If I add a number it gets rid of that. If I add another letter we get rid of that.

Now, I've also added this "Please Hack Me" button which, what this does is it will just directly set user.password to the string PWD.

If we go and click that it's going to reset that value to PWD. You see our warnings come back because we're no longer meeting either one of those requirements.

An alternative way to monitor user.password for changes is to use the ng-change directive. If we add that here and have ng-change we're going to call onChange. Let's get rid of this $scope.$watch so we're not actually going to be watching that value anymore.

We'll replace that with this $scope.onChange function. When the value changes we're going to pass $scope.user.password to that same checkPassword function.

If we go test this, if we refresh you can see we get the same behavior here that we did before but this time, if I click "Please Hack Me," you can see the value change but we don't get our warnings back.

The reason for that is ng-change only reacts to changes in the actual form element that you have declared it on. If your value changes programmatically as the result of anything but actually interacting with the element ng-change is not going to fire.

Keep that in mind when choosing between the two methods of monitoring a value.

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