9

I am using ng-include src directive at multiple places in my HTML. Each ng-include is creating an isolated scope for itself which apparently is causing a lot of trouble for me.

For example.

<div ng-controller="parent">
    <div ng-include src="'id1'">
    </div>
    <div ng-include src="'id2'">
    </div>
    <div ng-include src="'id2'">
    </div>
</div>

In the html mentioned above, 4 scopes are getting created. 1 at parent where controller is defined and 3 are getting created by default at each ng-include src.

Is it at all possible to prevent ng-include from creating an isolated scope for itself? If It is not possible then is there a workaround for it?

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
Aditya Ponkshe
  • 3,840
  • 4
  • 39
  • 58
  • simply create your own directive and load template through it, without declaring isolated scope – Pankaj Parkar Mar 18 '15 at 06:20
  • @pankajparkar How? Do you have any example as to how it can be done? – Aditya Ponkshe Mar 18 '15 at 06:21
  • ng-include doesn't create an isolated scope - it creates a child scope that is not isolated from the parent. Before you reinvent the wheel with a new directive, I'd be interested to understand what kind of trouble is being caused. A child scope is created for a reason - it prevents the templates from interfering with each other. – Joe Enzminger Mar 18 '15 at 06:40
  • @JoeEnzminger `ng-model` used in those templated, loaded by 'ng-include src' are not updated in parent controller. – Aditya Ponkshe Mar 18 '15 at 06:43
  • This is the classic "dot notation" problem in Angular. [The first and second answers to this question](http://stackoverflow.com/questions/17606936/angularjs-dot-in-ng-model) should shed some light on a better way to address your issue. It can also be solved by using the "ControllerAs" syntax. – Joe Enzminger Mar 18 '15 at 06:46
  • @JoeEnzminger I am aware of it. To implement this I'll have to change a whole lot of code which I am planning to do later on. Was looking for a quick solution for now. – Aditya Ponkshe Mar 18 '15 at 07:06
  • This answer creates a directive similar to ng-repeat without an isolate scope: http://stackoverflow.com/a/17340138/1221537 – adamdport Aug 10 '16 at 15:01

1 Answers1

19

You need to create a your own directive that can load specified template withoud isolated scope.

HTML

<div ng-controller="parent">
    <div my-directive template-path="id1">
    </div>
    <div my-directive template-path="id2">
    </div>
    <div my-directive template-path="id2">
    </div>
</div>

Directive

.directive('myDirective', function() {
  return {
      restrict: 'AE',
      templateUrl: function(ele, attrs) {
          return attrs.templatePath;
      }
  };
});

Working Plunkr

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299