解释这个表是如何创建angularjs的

时间:2015-02-06 09:39:07

标签: html angularjs

我在某个地方搜索过,发现了我需要的代码。我正在工作,想知道如何使用angularjs生成此表。我的意思是我不明白这个过程。我对此感到困惑tdCells[primaryarray][tdCells[primaryarray].length] = i+1 ;使用它可以帮助我解决问题



var app = angular.module("myApp", []);
app.controller('check', function($scope) {
  $scope.totalSeats = 20;
  $scope.seatArr = [];
  for (var i = 1; i <= $scope.totalSeats; i++) {
    $scope.seatArr.push(i);
  }

  console.log($scope.seatsArr);

  $scope.myData = [{
    seatno: '1',
    name: 'Melanie',
    ticketnNo: "abc456",
    insuranceNo: 34
  }, {
    seatno: '2',
    name: 'JOsefa',
    ticketnNo: "abc231",
    insuranceNo: 90
  }, {
    seatno: '17',
    name: 'Luna Marie',
    ticketnNo: "abc324",
    insuranceNo: 35
  }, {
    seatno: '5',
    name: 'Jana',
    ticketnNo: "abc221",
    insuranceNo: 91
  }, {
    seatno: '18',
    name: 'Scott Tooker',
    ticketnNo: "abc453",
    insuranceNo: 36
  }, {
    seatno: '6',
    name: 'Malanies Santos',
    ticketnNo: "abc241",
    insuranceNo: 93
  }, {
    seatno: '20',
    name: 'Luna Marie Landiola',
    ticketnNo: "abc322",
    insuranceNo: 39
  }, {
    seatno: '6',
    name: 'Eliza',
    ticketnNo: "abc222",
    insuranceNo: 92
  } ];
  
  $scope.getName = function(number){
      console.log(number);
      for(var i=0;i<$scope.myData.length;i++){
          if(number == $scope.myData[i].seatno)
              return $scope.myData[i].name;
      }
       return '';
  };
  var tdCells = [];
  var primaryarray=-1;
  for(var i=0;i<$scope.totalSeats;i++){
     if(i%3 ===0){
      ++primaryarray;          
      tdCells[primaryarray] = [];
     }
    
    tdCells[primaryarray][tdCells[primaryarray].length] = i+1 ;        
            tdCells[primaryarray][tdCells[primaryarray].length] = 
        $scope.getName(i+1);                  
  }
  $scope.rows = tdCells;
  console.log($scope.rows);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="check">
  <table border="1" width="100%">
    <colgroup span="7"></colgroup>
    <tbody>
      <tr ng-repeat="tr in rows">
        <td ng-repeat="td in tr">
          {{ td }}
        </td>
      </tr>
    </tbody>
  </table>
  </body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

在您的代码中,$scope.getName(number)函数很简单,它根据座位号从您的数据数组中获取名称。

以后的for循环有点棘手。它的作用我认为是: -

  • 它会创建一个包含三列(tdCells
  • 的二维数组if(i%3===0)
  • 对于此2D数组tdCells中的每一行: -
    • 它将第一个元素设置为seatnumber tdCells[primaryarray][tdCells[primaryarray].length] = i+1 ;
    • 它使用上面的函数$scope.getName(...)将第二个元素设置为名称。 tdCells[primaryarray][tdCells[primaryarray].length] = $scope.getName(i+1);

在ng-repeat中,它只是在标准列中呈现2D数组 - 只是每列都成为一对座位号和名称。

HTH!