把数组放在两个表中

时间:2017-10-19 18:36:43

标签: javascript angularjs arrays angularjs-ng-repeat

我需要使用ng-repeat将数组的结果放在两个表中。我有这个数组。

            $scope.times = [
            {"time": "20", "id": 0},
            {"time": "50", "id": 1},
            {"time": "30", "id": 2},
            {"time": "10", "id": 3},
            {"time": "85", "id": 4},
            {"time": "75", "id": 5},
            {"time": "95", "id": 6},

        ];

我只需要将前4个值放在一个表中,例如第一个表中的id 0,1,2,3和第二个表中的4,5,6。我不知道如何才能使用此功能但不起作用。

        $scope.verfica = function () {
        $scope.temp = [];
        $scope.temp2 = [];
        if (!$scope.times) {
            return;
        }
        for (var i = 0; i <= 3; i++) {
            $scope.temp[i] = $scope.times[i];
        }
        if ($scope.times.length > 7) {
            $scope.v = 1;
            for (var i = 3; i < $scope.times.length; i++) {
                $scope.temp2[i] = $scope.times[i];
            }
        }
    }

使用ng-repeat将temp放在第一个表中,将temp2放在第二个表中。但它没有任何想法或解决方案吗?

3 个答案:

答案 0 :(得分:0)

您只需使用array.slice

即可
 $scope.firstTable = $scope.times.slice(0, 3);
 $scope.secondTable = $scope.times.slice(3, 6);

<强>样本

&#13;
&#13;
var app =angular.module('testApp',[]);

app.controller('testCtrl',function($scope){
   $scope.times = [
            {"time": "20", "id": 0},
            {"time": "50", "id": 1},
            {"time": "30", "id": 2},
            {"time": "10", "id": 3},
            {"time": "85", "id": 4},
            {"time": "75", "id": 5},
            {"time": "95", "id": 6},

        ];
        
    $scope.firstTable = $scope.times.slice(0, 3);
    $scope.secondTable = $scope.times.slice(3, 6);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl">
  <div ng-repeat="arr in firstTable">
    <h1> first: {{arr.time}} </h1>
  </div>
  <div ng-repeat="arr in secondTable">
   <h1> second: {{arr.time}} </h1>
  </div>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以取数组的长度并将其除以2并将其四舍五入以进行切片。

var $scope = { times: [{ time: "20", id: 0 }, { time: "50", id: 1 }, { time: "30", id: 2 }, { time: "10", id: 3 }, { time: "85", id: 4 }, { time: "75", id: 5 }, { time: "95", id: 6 }] },
    part1 = $scope.times.slice(0, Math.round($scope.times.length / 2)),
    part2 = $scope.times.slice(Math.round($scope.times.length / 2));

console.log(part1);
console.log(part2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

我更喜欢.splice();这个方法实际上是从原始数组中返回元素,返回给定索引处的元素。

   $scope.verfica = function () {
    $scope.temp = [];
    $scope.temp2 = [];
    if (!$scope.times) {
        return;
    }
   for (var i = 0; i <= $scope.times.length; i++) {
   if (i <= 3) {
     var temp = $scope.times.splice(i, 1)
     $scope.temp.push(temp);
   } 
   else if(i>3) {
    var temp = $scope.times.splice(i, 1); 
      $scope.temp2.push(temp);
         }
    }
 }