防止 `ng-include` 创建隔离的作用域.AngularJS [英] Prevent `ng-include` from creating isolated scope. AngularJS

查看:20
本文介绍了防止 `ng-include` 创建隔离的作用域.AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如.

<div ng-include src="'id1'">

<div ng-include src="'id2'">

<div ng-include src="'id2'">

在上面提到的 html 中,正在创建 4 个范围.1 在定义了 controller 的父级,默认情况下在每个 ng-include src 处创建了 3 个.

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

解决方案

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

HTML

<div my-directive template-path="id1">

<div my-directive template-path="id2">

<div my-directive template-path="id2">

指令

.directive('myDirective', function() {返回 {限制:'AE',templateUrl: 函数(ele, attrs) {返回 attrs.templatePath;}};});

工作 Plunkr

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?

解决方案

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

这篇关于防止 `ng-include` 创建隔离的作用域.AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆