javascript - 防止 `ng-include` 创建隔离作用域。 AngularJS

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

我在 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 的父级,3 个在每个 ng-include src 中默认创建。

是否有可能阻止 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

关于javascript - 防止 `ng-include` 创建隔离作用域。 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29115207/

相关文章:

javascript - jQuery .val ('' ) 不清除文本区域输入

javascript - Angular/Ionic - 代码暴露会导致什么问题?

javascript - 从 Javascript 调用 swift 代码

javascript - 隐藏 DIV 内的 ASP.NET CheckBox 始终返回 false

javascript - 上下文结帐中的 Paypal - 防止页面重定向

javascript - HTML5 模式与哈希模式 AngularJS 的优点/缺点

javascript - 如何将 ngOptions 与包含 HTML 实体的字符串一起使用?

javascript - Angular UI-Grid 通过严格匹配过滤

javascript - 如何轻松地与父范围通信

javascript - AngularJs 使用指令中的输入字段验证表单