Angular JS排序和将字符串转换为整数

时间:2014-04-21 18:53:41

标签: javascript json angularjs

我目前正面临并在这里问题,我似乎无法绕过。我有一个包含一组人的json,每个人里面都有另一个字符串数组。在数组中,我有数字和实际的字符串值。整数本身被视为字符串,因此当我使用orderby时,它排序错误,因为它认为整数是字符串。

我想弄清楚的是我可以将字符串转换为整数,因为我使用ng-repeat来吐出整数。

这是我目前的HTML:

<div ng-controller="TableCtrl">
    <p><strong>Page:</strong> {{tableParams.page()}}</p>
        <p><strong>Count per page:</strong> {{tableParams.count()}}</p>
    <table ng-table="tableParams">
        <tr ng-repeat="person in $data">
        <td data-title="'Name'" sortable="'0'">{{person[0]}} {{person[1]}}</td>
        <td data-title="'Age'" sortable="'2'">{{ person[2] }}</td>
        </tr>
    </table>
</div>

当前的JSON结构:

0: Array[3]
0: "John"
1: "Doe"
2: "25"

我的javascript:

angular.module("myApp").controller('TableCtrl', ['$scope', '$http', 'ngTableParams', '$filter',

        function($scope, $http, ngTableParams, $filter) {
            $scope.People= {};
            $scope.tableParams = new ngTableParams({
                page: 1, // show first page
                count: 10 // count per page
            }, {
                total: 0, // length of data
                getData: function($defer, params) {
                    $http({
                        method: 'GET',
                        url: "json.url.json"
                    })
                        .success(function(data, status, headers, config) {

                            $scope.tableParams.total(data.length)

                            $scope.People= data;

                            var orderedData = params.sorting() ?
                                $filter('orderBy')(data, params.orderBy()) :
                                data;

                            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                        })
                        .error(function(data, status, headers, config) {
                            // something went wrong :(
                        });
                }
            });
        }
    ]);

目前正在使用http://bazalt-cms.com/ng-table/来尝试执行表和排序功能。

1 个答案:

答案 0 :(得分:0)

我通常只对数据进行一些预处理,因为它可以创建能够排序的字段等。

angular.forEach(data,function(el,i){
  el.age_int = parseInt(el.age);
});

$scope.people = data;

然后,您可以使用新字段进行排序或任何需要整数字符串的内容。