ng-repeat 访问对象内部的数组

ng-repeat to access array inside of objects

我有一个包含对象列表的数组。每个对象还包括一个数组(见下文)。我正在使用 ng-repeat 遍历每个对象的子数组,我尝试了很多不同的方法,但它根本不起作用。任何提示,方向,帮助将不胜感激。谢谢你。 :-)

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
<script>
    angular.module('mlApp', [])
       .controller('mlCtrl', [function () {
          var self = this;
          self.contacts = [
            { contact: 'AAA', mlist: [1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1] },
            { contact: 'BBB', mlist: [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1,1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1] }

          ];
 } ]);

<div ng-app="mlApp" ng-controller="mlCtrl as mCtrl">
<table>
<thead>..</thead>
<tbody>
    <tr ng-repeat="p in mCtrl.contacts">
        <th width="100px" >{{p.contact}}</th>
        <td ng-repeat="c1 in p.mlist"><input type="checkbox" ng-check='{{c1}}' /></td>
    </tr>

</tbody>
</table>
</div>

提示是检查控制台 errors - Angular(通常)对此类事情很有帮助。

你在内部 ng-repeat 中使用的数组中有重复的值,因此你需要通过某些东西来跟踪它。我在这个例子中使用了 $index:

angular.module('mlApp', [])
  .controller('mlCtrl', [
    function() {
      var self = this;
      self.contacts = [{
          contact: 'AAA',
          mlist: [1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1]
        }, {
          contact: 'BBB',
          mlist: [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
        }

      ];
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mlApp" ng-controller="mlCtrl as mCtrl">
  <table>
    <thead>..</thead>
    <tbody>
      <tr ng-repeat="p in mCtrl.contacts">
        <th width="100px">{{p.contact}}</th>
        <td ng-repeat="c1 in p.mlist track by $index">
          <input type="checkbox" ng-check='{{c1}}' />
        </td>
      </tr>

    </tbody>
  </table>
</div>

同样你可以这样做:

var myApp = angular.module('myApp',[]);

myApp.controller('mycontroller',['$scope',function($scope){
  
  $scope.students=[];
  var i=0;
  for(i=0;i<5;i++){
    var item={Name:'',Marks:[]};
  
    item.Name='student' + i;  
    item.Marks.push({Maths:50-i,Science:50 +i});
    
    $scope.students.push(item);
  }

}]);
<html ng-app='myApp'>
  <head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
</head>
  <body ng-controller='mycontroller'>
    <div ng-repeat='student in students'>
      Name : {{student.Name}} 
      <span ng-repeat="m in student.Marks">Maths:{{m.Maths}} Science:{{m.Science}}</span>
      </div>
  </body>
</html>