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

时间:2016-09-28 09:15:00

标签: 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的链接上看到它完美无缺。

P.S。这是我实际想要实现的原型。 主要是我在ng-repeat中存在的动态ng-include中使用的变量存在问题。

我检查了类似的问题,但未得到任何答案。

1 2 3

3 个答案:

答案 0 :(得分:2)

ng-include指令不会创建新的$scope对象,但会原型继承它,因此您的profile会被其他值覆盖。

首先,您说profile=theStudent,然后用profile=theTeacher覆盖它,因此在两个模板中,它始终设置为教师。

有一点&#39; hack&#39;要通过添加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> 对象:

{{1}}

请参阅this updated plunker

答案 1 :(得分:1)

您可以创建一个带有隔离范围的简单ng-include指令,而不是同时使用ng-ifprofile指令来实现您想要的内容,并将数据传递给它。

plucker

angular.module('ng-include-example', []).
controller("MainCtrl", function($scope) {

  var data = [
       {
         "student" : { "id":11, "name": "John" },
         "teacher" : { "id" : 21, "name": "Mike"}
       },
       {
         "student" : { "id":12, "name": "Tony" },
         "teacher" : { "id" : 22, "name": "Jack"}
       },
       {
         "student" : { "id":13, "name": "Cris" },
         "teacher" : { "id" : 23, "name": "Anthony"}
       },
       {
         "student" : { "id":14, "name": "Greg" },
         "teacher" : { "id" : 24, "name": "Reva"}
       }

    ];

    $scope.data = data;

})
.directive("profile", function(){
  return{
    restrict:'E',
    scope:{
      profile: "="
    },
    templateUrl: "profile.html"
  }
});

<div>
  Using Directive
  <table style>
      <tr>
        <th>Student</th>
        <th>Teacher</th>
      </tr>
      <tbody ng-repeat="val in data">
        <tr>
          <td>
            <profile profile = "val.student"></profile>
          </td>
          <td>
            <profile profile = "val.teacher"></profile>
          </td>
        </tr>
      </tbody>
    </table>
  </div>

答案 2 :(得分:0)

您还可以创建第二个html作为profile.html,并在您的代码之后:

<强>的index.html

<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="'profile2.html'" onLoad="profile2=val.teacher"></div>
          </td>
        </tr>
      </tbody>

<强> profile2.html

<span>Id - {{profile2.id}}</span>
<span>Name - {{profile2.name}}</span>
相关问题