Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    ngModelController: viewValue-modelValue relationship


    This lesson takes a look at the AngularJS internals to better understand what Angular is doing under the hood with ngModel to keep data and views in sync.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Man 1: Before we can discuss the proper use cases of NgModelController we first need to understand how the view value and the model value interact with each other.

    This block of code right here is the one that deals with the view value going into the model value. First, the view value is assigned to the value. Second, it handles all the pristine, dirty stuff for updating forms and adding classes for animations and stuff for forms.

    Third, it runs through all of the parsers. It will assign the value to whatever the parsers give you back. It parses the view stuff and prepares it to be assigned to the model. Then it checks to see if the model is the same as that output from the parsers. If it is not, then it assigns it and then it will trigger everything you have before the view change listeners, like NgChange.

    If you scroll down a little bit more, down to this section here this block of code is what handles the model changing the view. There's a scope watch which is just going to fire on every digest. It's going to check the NgModel attribute.

    If, for some reason, that attribute doesn't match the current model value it will run it through the formatters, set the model value to the value before it's formatted, and the output of the formatting will be assigned to the view value.

    Basically if value was a phone number that was just a string of digits without any dashes and that had changed, it will make sure it stores that value in the model value, format it to the dashes, and then assign the dashed version to the view value so that it can render it and show the dashed value.

    To recap, we have set the view value, run it through some parsers to check if it's either valid or convert it to a different format, then store it in the model value. And then, for the model to the view we watch to see if the model value ever changes. We format it to present it to the view. Once it's formatted then we push it out to the view and render.

    Angular watches the model value for you and will update the view value automatically whereas you have to tell Angular when you want to set the view value and then handle when you're going to apply and render the updates.