javascript - ng-repeat 与动态 ng-include 和模板变量范围问题

标签 javascript angularjs variables angularjs-ng-repeat angularjs-ng-include

当 ng-repeat 对变量进行动态 ng-include 时,它​​没有正确获取变量。

查看此 plunker .

主要的html代码

<table style>
  <tr>
    <th>Student</th>
    <th>Teacher</th>
  </tr>
  <tbody ng-repeat="val in data">
    <tr>
      <td>
        <div ng-include src="'profile.html'" onLoad="profile=val.student"></div>
      </td>
      <td>
        <div ng-include src="'profile.html'" onLoad="profile=val.teacher"></div>
      </td>
    </tr>
  </tbody>
</table>

profile.html代码

<span>Id - {{profile.id}}</span>
<span>Name - {{profile.name}}</span>

您可以在没有 ng-include 的链接中看到它工作完美。

附言这是我实际想要实现的原型(prototype)。 主要是我对 ng-repeat 中存在的动态 ng-include 中使用的变量有疑问。

我检查了如下类似的问题,但没有得到任何答案。

1 2 3

最佳答案

ng-include 指令不会创建新的 $scope 对象,但原型(prototype)会继承它,因此您的 profile 会被另一个覆盖值(value)。

所以首先你说 profile=theStudent 然后你用 profile=theTeacher 覆盖它,因此在两个模板中它总是设置为教师。

通过添加 ng-if="true" 可以解决这个问题,它会创建一个新的 $scope 对象:

<tbody ng-repeat="val in data">
    <tr>
        <td>
            <div ng-include src="'profile.html'"
                 onLoad="profile=val.student"
                 ng-if="true"></div>
        </td>
        <td>
            <div ng-include src="'profile.html'" 
                 onLoad="profile=val.teacher"
                 ng-if="true"></div>
        </td>
    </tr>
</tbody>

参见 this updated plunker

关于javascript - ng-repeat 与动态 ng-include 和模板变量范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39742976/

相关文章:

variables - 将环境变量传递到 Tomcat 7.0 Web 应用上下文

javascript - 使用 javascript 的替换通配符来更改字符串内的宽度属性

javascript - 防止传递给 JS 代码文件的参数的 XSS

javascript - 华丽的弹出式透明 png 为灰色

angularjs - ionic 框架和 Angular ui 日历问题?

angularjs - 无法加载 PDF 文档 - Angular JS - BLOB

javascript - 帮助 JQuery 条件语句

Android 4.1 库存浏览器 : Can't open links in new tab

java - 我需要在 AsyncTask 执行中传递一个变量,但不知道如何执行

Python:不重新分配变量