【问题标题】:Prevent `ng-include` from creating isolated scope. AngularJS防止 `ng-include` 创建隔离范围。 AngularJS
【发布时间】:2015-05-20 19:59:24
【问题描述】:

我在我的 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 为自己创建一个孤立的范围?如果不可能,那么是否有解决方法?

【问题讨论】:

  • 只需创建自己的指令并通过它加载模板,无需声明隔离范围
  • @pankajparkar 怎么样?你有什么例子可以说明如何做到的吗?
  • ng-include 不会创建一个独立的作用域——它会创建一个不与父作用域隔离的子作用域。在您使用新指令重新发明轮子之前,我很想了解正在造成什么样的麻烦。子范围的创建是有原因的 - 它可以防止模板相互干扰。
  • @JoeEnzminger ng-model 在那些模板中使用,由“ng-include src”加载,不会在父控制器中更新。
  • 这是 Angular 中经典的“点符号”问题。 The first and second answers to this question 应该能够更好地解决您的问题。也可以使用“ControllerAs”语法来解决。

标签: javascript angularjs angularjs-directive directive angularjs-ng-include


【解决方案1】:

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

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

【讨论】:

  • 它没有返回任何东西。
  • @AdityaPonkshe 看到我更新的答案,在指令中添加了restrict: 'AE' 属性支持
  • 成功了!非常感谢。我最终在指令中的 templateurl 处给出了硬编码路径,但它解决了范围问题。 +1 解决方案。
  • 不,你不应该硬编码它,那么它就不会被用作可重用组件
  • 嗯,是的,但是当我使用function(ele, attrs) { return attrs.templatePath; } 时出现一些错误,目前正在修复它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
  • 2012-06-25
  • 2014-02-17
  • 1970-01-01
  • 2015-04-17
  • 2015-03-17
  • 1970-01-01
相关资源
最近更新 更多