AngularJS:如何对angularjs中的表应用排序/反向排序?

时间:2016-06-20 19:17:23

标签: javascript angularjs sorting

我有HTML部分,如下所示。我用ng-repeat填充标题,也可以按钮添加标题。如果有人可以通过点击表格列来帮助我如何对数据进行排序和反向排序。我一次只能使单个属性工作,无论是按列添加还是按数据排序。

<input type="text" ng-model="newColumn" placeholder="Add Column Name">
<button class="btn-cstm" ng-click="addColumn()">Add Column</button>

<div>
<table>
    <tr>
        <th ng-repeat="column in columns" ng-click="sortBy(column)">    {{column}}</th>
    </tr>
    <tr ng-repeat="row in rows | orderBy:propertyName:reverse">
        <td ng-repeat="entry in entries">{{row[entry]}}</td>
    </tr>
</table>

我的控制器如下:

$scope.columns = [];
$scope.rows = [];
$scope.entries = [];
$scope.newColumn = " ";
$scope.addColumn = function() {
    var counter = $scope.columns.length + 1;
    $scope.columns.push($scope.newColumn + counter);
};
var dataContainer = [
    {name: 'John',   phone: '555-1212',  age: 10},
    {name: 'Mary',   phone: '555-9876',  age: 19},
    {name: 'Mike',   phone: '555-4321',  age: 21},
    {name: 'Adam',   phone: '555-5678',  age: 35},
    {name: 'Julie',  phone: '555-8765',  age: 29}
];
angular.forEach(dataContainer, function (values) {
    $scope.rows.push(values)
});
$scope.container = {
    name: "Name",
    phone: "Phone Number",
    age: "Age"
};
angular.forEach($scope.container, function (values, keys) {
    $scope.columns.push(values);
    $scope.entries.push(keys);
});

$scope.propertyName = 'name';
$scope.reverse = true;
$scope.dataContainer = dataContainer;
$scope.sortBy = function (propertyName) {
    $scope.reverse = ($scope.propertyName === propertyName) ?     !$scope.reverse : false;
        $scope.propertyName = propertyName;
}

这是我对数据属性排序正确的方法。 改变控制器:

替换

 angular.forEach($scope.container, function (values, keys) {
    $scope.columns.push(values);
    $scope.entries.push(keys);
});

$scope.columns = $scope.container;

HTML更改: 取代

<table>
    <tr>
        <th ng-repeat="column in columns" ng-click="sortBy(column)">{{column}}</th>
    </tr>
    <tr ng-repeat="row in rows | orderBy:propertyName:reverse">
        <td ng-repeat="entry in entries">{{row[entry]}}</td>
    </tr>
</table>

<table>
    <tr>
        <th ng-repeat="(key, value) in columns" ng-click="sortBy(key)">{{value}}</th>
    </tr>
    <tr ng-repeat="row in rows | orderBy:propertyName:reverse">
        <td ng-repeat="(key, value) in columns">{{row[key]}}</td>
    </tr>
</table>

但是addColumn不起作用,因为我没有通过推入列数组来填充表。如果有人可以帮助我,我会说你的时间。

0 个答案:

没有答案