1

I have two text inputs, one in root scope, and the other in a controller's scope,

<input type="text" ng-model="message">

When I give "q" in the first input, there is a property "message" created in the root scope. When I give "a" in the second input, there is a property "message" created in the controller's scope.

Now I introduce an object in the scopes,

<input type="text" ng-model="data.message">

When I give "q" in the first input, there is a property "data" created in the root scope. When I give "a" in the second input, there is NOT a property "data" created in the controller's scope.

Why is this?

Thanks,

Eric J.

ericj
  • 2,138
  • 27
  • 44

1 Answers1

1

Angular scopes rely on Javascript Prototypal inheritance.

What it boils down to is this, if you set a property on a scope then any child scope will be able to read it. If you want to write back to that property you would have to explicitly get the scope that it was set on, otherwise it creates what is known as a "shadow" model, this is where you have set a property on a parent scope and then overridden it in a child scope.

The way around this is to do as you have discovered, set a property on a scope to be an object, then any time you set a property on that object the object attached to the scope gets updated and not the scope. As your object is a plain old js object it works as you expect, being able to be updated and read where you like.

Derek Ekins
  • 11,215
  • 6
  • 61
  • 71