防止 `ng-include` 创建独立的范围。 AngularJS

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

我在 HTML 的多个地方使用了 ng-include src 指令。每个 ng-include 都在为自己创建一个独立的范围,这显然给我带来了很多麻烦。

例如。

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

在上面提到的 html 中,正在创建 4 个作用域。 1 个在定义 controller 的父级,默认情况下在每个 ng-include src.

创建 3 个

是否有可能阻止 ng-include 为自己创建一个独立的作用域?如果不可能,那么有解决方法吗?

您需要创建一个您自己的指令,它可以在没有隔离范围的情况下加载指定的模板。

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('myDirective', function() {
  return {
      restrict: 'AE',
      templateUrl: function(ele, attrs) {
          return attrs.templatePath;
      }
  };
});

Working Plunkr