Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: modifying parent scope in ng-include

I found this thread in which the OP's original fiddle where an ng-included 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?

like image 526
jogloran Avatar asked Feb 20 '13 02:02

jogloran


1 Answers

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?

like image 95
Mark Rajcok Avatar answered Nov 29 '22 04:11

Mark Rajcok