【问题标题】:How to display array in table using ng-repeat如何使用 ng-repeat 在表格中显示数组
【发布时间】:2019-09-04 01:59:24
【问题描述】:

与其他 JSON 数据不同,我有两个简单的数组。

$scope.land = [ elephant, tiger, zebra ];
$scope.water = [ fish , octopus, crab];

我想使用ng-repeat 将数组放入表格中。我试过了,但数据没有以正确的格式显示。

<table class="table table-dark">
    <thead>
        <tr>
            <th scope="col">LAND</th>
            <th scope="col">WATER</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="l in land track by $index">
            <td>{{l}}</td>
            <td>fish</td>
        </tr>
    </tbody>
</table> 

编辑:- 数据在表格中显示垂直时出错 enter image description here

新数据:-

$scope.land = [ 'tiger in zoo', 'tiger in jungle', 'zebra'];
 $scope.water = [ 'fish in pond'];

【问题讨论】:

  • 使用控制器中的 JS 代码将两个数组压缩成一个数组:[{land:elephant, water:fish}, {land:tiger, water:octopus},...],然后使用一个简单的、传统的 ng-repreat 显示这个数组中的每个对象。
  • @JBNizet 必须要有一个吗?
  • 不,但这是最简单、最明显、最有效的方法。
  • @JBNizet 我明白了,但我无法更改数组,如果以这种方式无论如何都可以,那么我的时间将被节省。
  • 你为什么不能这样做?如果您开发 AngularJS 应用程序,那么您应该在某个时候编写一些 JS 代码,而不仅仅是 HTML 代码。控制器的作用是让视图更容易显示内容。所以是的,你可以这样做,你应该这样做。没有正当理由你不能这样做。

标签: angularjs html-table angularjs-ng-repeat


【解决方案1】:

我认为您正在尝试将两个数组的元素并排显示(如果我错了,请纠正我)。

这是一个简单的方法:

angular.module('myApp', [])
.controller('TestCtrl', function ($scope) {
    $scope.land = [ 'tiger in zoo', 'tiger in jungle', 'zebra'];
    $scope.water = [ 'fish in pond'];
    $scope.combined = [];
    var maxLength = ($scope.land.length > $scope.water.length) ? $scope.land.length : $scope.water.length;
    //length is to be determined
    for(var index = 0; index < maxLength ; index++) {
    	$scope.combined.push({
      	land: ($scope.land[index]) ?  $scope.land[index] : '',
        water: ($scope.water[index]) ? $scope.water[index] : ''
      });
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="TestCtrl">
  <table class="table table-dark">
    <thead>
      <tr>
        <th scope="col">LAND</th>
        <th scope="col">WATER</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in combined">
        <td>{{item.land}}</td>
        <td>{{item.water}}</td>
      </tr>
    </tbody>
  </table> 
</div>

【讨论】:

  • 是的,非常感谢。但是为什么只确定土地长度scope.land.length
  • 我的数据也以垂直方式显示。你能猜到为什么吗?我在编辑中添加图片
  • 循环正在遍历土地数组,如果它们具有相同数量的元素,也可以是水,我放置该评论仅供参考
  • 两边都可以有更多和更少。那怎么可能呢?
  • 在这种情况下,您可以采用最长的数组并将项目数放入循环中。我已经为那个案例更新了 sn-p
猜你喜欢
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
相关资源
最近更新 更多