【问题标题】:Angular JS sorting and converting strings to integersAngular JS对字符串进行排序并将其转换为整数
【发布时间】:2014-04-22 02:56:32
【问题描述】:

我目前在这里遇到问题,我似乎无法解决。我有一个 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/ 来尝试执行表格和排序功能。

【问题讨论】:

    标签: javascript json angularjs


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-06-16
      • 2017-07-28
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      相关资源
      最近更新 更多