使用AngularJS向表中添加列

时间:2017-03-23 07:31:56

标签: javascript angularjs loops

如果按下按钮,我尝试添加列,但没有成功。 我问了我JSFiddle example。 如果有人可以帮我解决这个问题,我将非常感激。

这是我的尝试:

$scope.addValue = function() {
      $scope.headers.push('new header');
      var users = 5;
      for(var i = 0; i < users; i++) {
          var rowData = [];
          for (var j = 0; j < 1; j++) {
              rowData.push('data i=' + i + ' j=' + j)
          }
          $scope.data.push(rowData);
      }
  };

1 个答案:

答案 0 :(得分:1)

以下是基于此JSFiddle的工作示例。

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

function MyCtrl($scope) {
  $scope.headers = [];
  $scope.data = [];
  $scope.colCount = 3;

  var data = [];

  // populate demo data
  for (var i = 0; i < 10; i++) {
    $scope.headers.push('Col ' + (i + 1));
    var rowData = [];
    for (var j = 0; j < 10; j++) {
      rowData.push('Row-' + (i + 1) + ' - Col ' + (j + 1))
    }
    data.push(rowData);
  }

  $scope.increment = function(dir) {
    (dir === 'up') ? $scope.colCount++: $scope.colCount--;
  }

  $scope.data = data;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <button ng-click="increment('up')">Add Column</button>
  <button ng-click="increment('down')">Remove Column</button>
  <table>
    <tr>
      <th ng-repeat="h in headers | limitTo: colCount">{{h}}</th>
    </tr>
    <tr ng-repeat="row in data">
      <td ng-repeat="item in row | limitTo: colCount">{{item}}</td>
    </tr>
  </table>
</div>