Why ng-model value should contain a dot

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Take our previous tutorial here, which works perfect fine like this shown here…

example run

example run

but is not best practice because ng-model value does not contain a dot.  The code looks like this …

no dot is bad

no dot is bad

While our simple case works fine. Let’s construct an example where it doesn’t work fine.  Add these HTML…

add these HTML

add these HTML

The key here is that ng-switch is a directive that creates a new scope.  There are other directives that does this.

To get the following…

The three boxes should be in sync

The three boxes should be in sync

When you type in the first box, the value shows up immediately in all three boxes.  This is as expected.  The problem is that now when you type into the second textbox, it value gets disconnected and the three box values are no longer in sync.

Why?  The answer is better explained the article by Jim Hoskins and Egghead.io has a video explaining.

The way to avoid this kind of thing is to use the best practice to having a ng-model value of something dot something.  Make it like this …

This is correct

This is correct

and now the code works with all three textbox always in sync.

Variables that change should not be attached directly to $scope.  Functions and objects can.

ng-model with dot is good.  And that was what we did in the subsequent tutorial.