Search code examples
javascriptangularjsangularjs-directivedirectiveangularjs-ng-include

Prevent `ng-include` from creating isolated scope. AngularJS


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?


Solution

  • 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