如何在角度js中重复数组

时间:2017-07-10 06:20:41

标签: javascript angularjs arrays

如何以角度ng-repeat数组,我想在我的视图中循环gpa

   [
  {
    "id": 1,
    "name": "Pre-Algebra",
    "selected": true,
    "gpa": [
      {
        "grade_date": null,
        "grade_type": null,
        "grade_percent": null,
        "letter_grade": null
      },
      {
        "grade_date": null,
        "grade_type": null,
        "grade_percent": null,
        "letter_grade": null
      }
    ]
  },
  {
    "id": 2,
    "name": "Pre-Calculus",
    "selected": true
  }
]

查看代码:

 <div ng-repeat="course in ctrl.subjectCourseGrades| filter: {selected  : true} track by $index">
 <table class="academy-table gpa-table" ng-class="!ctrl.editAcademyToggle?'data-view':''">
        <tr ng-repeat="gpa in course.gpa" ng-if="!ctrl.editAcademyToggle" class="ots-data">
            <td>
                <b>Id is  : {{$index}}<span ng-bind="gpa.grade_date"></span></b>
            </td>
        </tr>
</table>
    </div>

我做错了什么?

2 个答案:

答案 0 :(得分:4)

您不需要在ngRepeat表达式中使用$index

使用

<tr ng-repeat="gpa in course.gpa"

而不是

<tr ng-repeat="gpa in course.gpa[$index]"

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  this.subjectCourseGrades = [{
    "id": 1,
    "name": "Pre-Algebra",
    "selected": true,
    "gpa": [{
        "grade_date": null,
        "grade_type": null,
        "grade_percent": null,
        "letter_grade": null
      },
      {
        "grade_date": null,
        "grade_type": null,
        "grade_percent": null,
        "letter_grade": null
      }
    ]
  }];
});
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>
  <div ng-app="myApp" ng-controller="myCtrl as ctrl">
    <div ng-repeat="course in ctrl.subjectCourseGrades | filter: {selected  : true} track by $index">
      <table class="academy-table gpa-table">
        <tr ng-repeat="gpa in course.gpa" class="ots-data">
          <td>
            <b>Id is  : {{$index}}<span ng-bind="gpa.grade_date"></span></b>
          </td>
        </tr>
      </table>
    </div>
  </div>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

从ng-repeat

中删除$index
<tr ng-repeat="gpa in course.gpa" ng-if="!ctrl.editAcademyToggle" class="ots-data">
            <td>
                <b>Id is  : {{$index}}<span ng-bind="gpa.grade_date"></span></b>
            </td>
        </tr>

Edit1:在查看了你的问题之后,似乎你正在使用控制器而不是$ scope。你需要这个:

<tr ng-repeat="gpa in ctrl.course.gpa"></tr>

编辑2:div不是有效的表元素。这可能是不工作的原因。使用tbody。

<tbody ng-repeat="course in ctrl.subjectCourseGrades| filter: {selected  : true} track by $index">
    <tr ng-repeat="gpa in course.gpa" ng-if="!ctrl.editAcademyToggle" class="ots-data">
        <td>
            <b>Id is  : {{$index}}<span ng-bind="gpa.grade_date"></span></b>
        </td>
    </tr>