Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Using the ngChange Directive in Angular

    Ben ClinkinbeardBen Clinkinbeard

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

    angularjsAngularJS
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Man 1: 00:00 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.

    00:24 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.

    00:36 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.

    00:48 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.

    01:01 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.

    01:28 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.

    01:43 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.

    02:00 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.

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

    Discuss

    Discuss