9

In AngularJS is it possible to inherit the parent controller's scope from within an included partial instead of passing the data through an injected service?

Example case:

Let's say ParentCtrl's scope looks like: { testData: 'testing stuff' }

<div ng-controller="ParentCtrl">
    Here we're defined: {{testData}}
    <div ng-include="'partial.html'"></div>
</div>

And inside partial.html:

<em>Inherited: {{testData}}</em>

So the partial doesn't even need it's own controller for this. If this is impossible though and you can only pass injected data between controllers via a service why has Angular done things this way?

saricden
  • 2,084
  • 4
  • 29
  • 40

2 Answers2

7

Yes, that's actually how it works by default. ng-include always creates a new scope and:

A "child scope" (prototypically) inherits properties from its parent scope.

See the docs on Scope.

Here is an example plunker.

Edit: Also, I just noticed a syntax issue in your original question. The template should be surrounded in single quotes. Change <div ng-include="partial.html"></div> to <div ng-include="'partial.html'"></div>

Noel
  • 3,288
  • 1
  • 23
  • 42
0

Playing around with the example Plunkr in the ngInclude documentation, I'm able to access the parent controller's scope from within the partial. For example, change the contents of template1.html to:

Content of template1.html {{ template }}

Per the docs, ngInclude creates a new scope, which means you'll need to observe the angular best practice of "having a dot in your scope" (accessing objects on the scope instead of primitive values), to avoid problems with broken references. You can check out this Stack Overflow question for more information.

Community
  • 1
  • 1
Problematic
  • 17,567
  • 10
  • 73
  • 85