如何在angularJS表中对自动增量序列号列进行排序?

时间:2015-12-08 13:13:18

标签: angularjs sorting angularjs-orderby

如何在angularjs表中对自动增量序列号列进行排序?

我的带有自动增量的序列号列,我需要排序列。

我的源代码是

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

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

<table>
    <thead>
        <tr>
            <th>S.No.</th>
            <th><a href="" ng-click="orderByField='Name'; reverseSort = !reverseSort">Name</a></th>
            <th><a href="" ng-click="orderByField='DOB'; reverseSort = !reverseSort">D.O.B.</a></th>
        </tr>
    </thead>
  <tr ng-repeat="x in names  | orderBy:orderByField:reverseSort">
        <td>{{ $index + 1 | number }}</td>
        <td>{{ x.Name }}</td>
        <td><span ng-if="x.DOB">{{ formatDate(x.DOB) |  date:'dd-MM-yyyy' }}</span></td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {

    $scope.names = [
        { Name: 'Jani', DOB: '' },
        { Name: 'Hege', DOB: '1995-05-07' },
        { Name: 'Kai', DOB: '1995-08-24' }
    ];

    $scope.formatDate = function (date) {
        return new Date(date);
    };

});
</script>

</body>
</html>

{{ $index + 1 }}标记内的自动增量部分为<td>

2 个答案:

答案 0 :(得分:0)

&#13;
&#13;
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Carl',country:'Sweden'},
        {name:'Margareth',country:'England'},
        {name:'Hege',country:'Norway'},
        {name:'Joe',country:'Denmark'},
        {name:'Gustav',country:'Sweden'},
        {name:'Birgit',country:'Denmark'},
        {name:'Mary',country:'England'},
        {name:'Kai',country:'Norway'}
        ];
    $scope.orderByMe = function(x) {
        $scope.myOrderBy = x;
    }
    
});
&#13;
table tr th{
cursor:pointer;
}

table tr th:hover{
background:#ddd;
}
&#13;
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<p>Click the table headers to change the sorting order:</p>

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

<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('num')">Sl.No</th>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy">
<td>{{$index + 1}}</td>
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>


</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在Angular 2+中,您可以这样使用:

<div *ngFor="let item of items; let ndx = index">
    <div>{{ndx+1}}</div>
</div>