4

Here are two snippets of code:

<input type="text" ng-model="data.message">
<div>Hello, {{data.message}}</div>

<div ng-controller="firstCtrl">
    <input type="text" ng-model="data.message">
    <div>Hello, {{data.message}}</div>
</div>

<div ng-controller="secondCtrl">
    <input type="text" ng-model="data.message">
    <div>Hello, {{data.message}}</div>
</div>

and

<input type="text" ng-model="msg">
<div>Hello, {{msg}}</div>

<div ng-controller="firstCtrl">
    <input type="text" ng-model="msg">
    <div>Hello, {{msg}}</div>
</div>

<div ng-controller="secondCtrl">
    <input type="text" ng-model="msg">
    <div>Hello, {{msg}}</div>
</div>

ng-controller here creates new scope so the firstCtrl and secondCtrl scope prototypically inherits from root scope in both cases. So, ideally, when the property of a children is overwritten is shadows the inherited value from parent and the value in parent stays same. Then why do the two snippets work differently?

Also, why in the first snippet, changing the value in firstCtrl changes the value in root scope as well?

Plnkr: http://plnkr.co/edit/x4LH4JAOMr9I8bCcSO8Y?p=preview

user1624400
  • 395
  • 4
  • 13
  • 4
    This should answer all your questions http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs?rq=1 – Chandermani Jun 03 '13 at 07:54
  • 1
    Root scope is changed because firstCtrl prototypically inherits from root scope. Since firstCtrl is modifying an object property, it checks the prototype chain and finds the object in the $rootScope, so it gets modified there. – Mark Rajcok Jun 03 '13 at 14:50
  • 1
    Thanks! The two comments above clear my doubt! – user1624400 Jun 03 '13 at 17:29

1 Answers1

1

The dot is used to sync the controllers so updating a property in one model will cause the property in the other controllers to be updated too.

In your second snippet you are overwriting the scope.

please see this video which explains it nicely.

ronen
  • 1,460
  • 2
  • 17
  • 35
  • 2
    What I wanted to know was why is the behavior like that? This explains it: http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs?rq=1 – user1624400 Jun 03 '13 at 17:31