How to split data by half when using ng-repeat?

I have some data and I can compile this data into a div using ng-repeat . I am trying to split them into 2 columns and cannot find a way to create them.

Here is my example: (jsFiddle)

HTML:

 <div ng-controller="Ctrl"> <div class="left"> <div ng-repeat="item in data">{{item.value}}</div> <!-- i've tried filter and failed --> </div> <div class="right"> <div ng-repeat="item in data">{{item.value}}</div> </div> </div> 

JS:

 var app = angular.module('app', []); function Ctrl($scope) { $scope.data = [ {value: "a"}, {value: "b"}, {value: "c"}, {value: "d"},// trying to divide from here {value: "e"},// and show the last part in other column {value: "f"}, {value: "g"}, {value: "h"} ]; } 
+5
source share
4 answers

You can use two variables, for example

 function Ctrl($scope) { $scope.data = [ {value: "a"}, {value: "b"}, {value: "c"}, {value: "d"},// trying to divide from here {value: "e"},// and show the last part in other column {value: "f"}, {value: "g"}, {value: "h"} ]; var len = $scope.data.length, mid = len / 2; $scope.left = $scope.data.slice(0, mid); $scope.right = $scope.data.slice(mid, len); } 

Example

+7
source

There is an even cleaner and simpler solution, but you should use Angular 1.2.1: https://jsfiddle.net/1fch1221/6/

 <div ng-controller="Ctrl"> <div class="left"> <div ng-repeat="item in data" ng-if="$index < (data.length / 2)">{{item.value}}</div> </div> <div class="right"> <div ng-repeat="item in data" ng-if="$index >= (data.length / 2)">{{item.value}}</div> </div> 

+15
source

I don't know, it's cleaner than the other answers, but as an idea:

 ng-repeat="item in data.slice(0, data.length / 2)" ng-repeat="item in data.slice(data.length / 2, data.length)" 
+2
source

I think the simplest solution here is to split the data array into two different variables. If you cannot do this, you can also encode a test function that decides to show or not a given value.

 <div ng-repeat="item in data" ng-show="test(item.value)" 

JSFiddle of my suggestion: here

+1
source

Source: https://habr.com/ru/post/1214826/


All Articles