Angularjs int过滤器未在智能表内正确排序

时间:2016-02-09 22:15:45

标签: javascript angularjs json sorting smart-table

我正在使用智能表在我的应用程序中的视图上显示我的数据(通过%http.get通过json文件加载)。

在视图的控制器中我创建了一个过滤器,因为来自json的返回数据中包含数字,这些数字作为数据类型字符串返回。过滤器尝试将数字作为INT数据类型返回,以便smart-table的排序功能将正确排序。

然而,无论我尝试什么,智能表排序仍然将值排序为String数据类型。

我的观点叫做Interfaces.html:

<div ng-controller="interfaceController">
    <div class="container">
        <table st-table="displayedCollection" st-safe-src="rowCollection" class="table table-striped" ng-show="displayedCollection">
            <thead>
                <tr>
                    <th st-sort="Name">Interface</th>
                    <th st-sort="Disabled">Disabled</th>
                    <th st-sort="Online">Online</th>
                    <th st-sort="Failed">Failed</th>
                    <th st-sort="Error">Error</th>
                    <th st-sort="Overdue">Overdue</th>
                </tr>
                <tr>
                    <th colspan="4"><input st-search="" class="form-control" placeholder="global search...." type="text"/></th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="row in displayedCollection">
                    <td>{{row.Name}}</td>
                    <td>{{row.Disabled | convertInt | number}}</td>
                    <td>{{row.Online}}</td>
                    <td>{{row.Failed}}</td>
                    <td>{{row.Error}}</td>
                    <td>{{row.Overdue}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

我的控制器名为interfaceController.js

app.controller('interfaceController',['$scope','$http', function($scope,$http){

    $http.get('app/data/InterfacesAuto.json').success(function(data,status,headers,config){
        $scope.rowCollection = data;

        $scope.displayedCollection = [].concat($scope.rowCollection);
    });

}]);

// Filter takes a value from the table and returns it as an INT
app.filter('convertInt',function(){
    return function (input) {
        this.parseInt = parseInt;
        return (parseInt(input,10));
    };
});

我正在加载的json

[
{"Name":"First","Disabled":"2","Online":"5","Failed":"1","Error":"0","Overdue":"2"},
{"Name":"Second","Disabled":"163","Online":"426","Failed":"7","Error":"0","Overdue":"195"},
{"Name":"Third","Disabled":"0","Online":"1","Failed":"0","Error":"0","Overdue":"0"}
]

我是angularjs和网页设计的新手,所以请提前感谢您的帮助。

干杯

1 个答案:

答案 0 :(得分:1)

您需要更改控制器中的数据类型。过滤器用于格式化数据以显示给用户。

也许你可以在收到服务器的数据后立即将字符串转换为int(我使用了jquery):

$( data).each(function( index, element ) {
          element.Disabled = parseInt(element.Disabled);
        });

<强>小提琴: http://jsfiddle.net/HB7LU/23575/

我使用过滤器按“已禁用”属性排序。

在角度服务中拥有此逻辑(ajax调用和数据处理)也是一个好主意。

希望它有所帮助。