jogloran
jogloran

Reputation: 992

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?

Upvotes: 5

Views: 5022

Answers (2)

James Harrington
James Harrington

Reputation: 3216

This directive will include a partial without creating a new scope. For an example you can create a form in the partial and control that form from the parent controller.

Here is a link to the Repo that i created for it.

I based my answer on this S.O. answer good luck :-)

Upvotes: 0

Mark Rajcok
Mark Rajcok

Reputation: 364697

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?

Upvotes: 7

Related Questions