Prevent `ng-include` from creating isolated scope.

2019-01-25 11:44发布

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?

1条回答
够拽才男人
2楼-- · 2019-01-25 12:26

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

查看更多
登录 后发表回答