Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit outer controller's scope from within ng-include without a service?

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?

like image 616
saricden Avatar asked Feb 03 '15 17:02

saricden


1 Answers

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>

like image 55
Noel Avatar answered Nov 07 '22 02:11

Noel