Angular passing scope to ng-include

Late to the party, but there is a little angular ‘hack’ to achieve this without implementing a dumb directive.

Adding a built-in directive that will extend your controller’s scope (like ng-if) everywhere you use the ng-include will actually let you isolate the variable name for all the included scopes.

So:

<div ng-include="'item.html'"
  ng-if="true"
  onload="item = rightItem">
</div>
<div ng-include="'item.html'"
  ng-if="true"
  onload="item = leftItem">
</div>

You can then bind your template item.html to the item variable several times with different items.

Here is a plunker to achieve what you want

The problem was the item keeps changing in the controller scope that only holds one reference to item variable which is erased at each onload instruction.

Introducing a directive that extends the current scope, lets you have a isolated scope for all the ng-include.
As a consequence the item reference is preserved and unique in all extended scope.

Leave a Comment