Search code examples
angularjsangularjs-ng-repeatangular-controller

How to repeat the Table Header Details for every 2 records


<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="customersCtrl"> 

<table>
  <tr>
    <th></th>
    <th>Name</th>
    <th>Country</th>
  </tr>
  <tr ng-repeat="x in names">
    <td>{{$index+1}}</td>
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .then(function (response) {$scope.names = response.data.records;});
});
</script>

</body>
</html>

Hai Guys,

I am using ng-repeat to display the table records and $index+1 to display the serial number.

I want to display the Header Name and Country to repeat for every 2 records(if $index %2 == 0). How will i do it? Any idea please.


Solution

  • Well i found my own answer.

     <!DOCTYPE html>
        <html>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <body>
    
        <div ng-app="myApp" ng-controller="customersCtrl"> 
        <div ng-repeat-start="x in names">
        </div>
        <div ng-if="$index % 2==0">
        <table ng-repeat="x in names | limitTo:1">
           <tr>
            <th>S No</th>
            <th>Name</th>
            <th>Country</th>
          </tr>
         </table>
        </div>
        <table ng-repeat-end="x in names">
          <tr>
            <td>{{$index + 1}}</td>
            <td>{{ x.Name }}</td>
            <td>{{ x.Country }}</td>
          </tr>
        </table>
    
        </div>
    
        <script>
        var app = angular.module('myApp', []);
        app.controller('customersCtrl', function($scope, $http) {
            $http.get("customers.php")
            .then(function (response) {$scope.names = response.data.records;});
        });
        </script>
    
        </body>
        </html>