I found this thread in which the OP's original fiddle where an ng-include
d scope doesn't modify its parent scope.
One of the replies suggests:
It is ugly and unpredictable, so i recommend you to wrap your data in an object variable: http://jsfiddle.net/e5rfP/3/
which seems to work. Why is this?
An object variable works because of the way JavaScript prototypal inheritance works. ngInclude creates its own child scope. This child scope prototypically inherits from the parent scope.
In JavaScript, when we write something like $scope.x = 22
in a child scope, this creates an x
property on the child $scope and assigns it the value 22 -- the prototype chain is not consulted here, so the parent $scope does not see what happened.
When we write something like $scope.someObj.prop1 = 22
on the child scope, if JavaScript doesn't find the someObj
object on the child $scope, it consults the prototype chain, and the next $scope in the chain is the parent $scope. If someObj
exists on the parent $scope, then the parent $scope is modified.
As I mentioned in a comment, the following SO question and answer explains this all in much more detail (with lots of pictures): What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With