我收到TypeError:从工厂ng-Table AngularJS加载数据时,无法调用undefined方法'slice'

时间:2013-11-21 07:38:30

标签: angularjs ngtable

我是AngularJS的新手,在使用来自服务的ng-Table时,他一直在显示数据。我收到了错误

TypeError:无法调用未定义的方法'slice'     at Object。$ scope.tableParams.ngTableParams.getData(index.html:122:32)

当我对json数据值进行硬编码时,它的工作正常。我认为来自工厂的数据不仅仅包含json数据结果,因此切片存在问题。

我的控制器看起来像这样:

myApp.controller('usersCtrl', function usersCtrl($scope, userData, $filter, ngTableParams, $log){

    userData.getUsers(function(users){
        $scope.users = users;
    })

    var users = $scope.users;

    $scope.$watch("filter.$", function () {
        $scope.tableParams.reload();
    });

    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 10,          // count per page
        sorting: {
            name: 'asc'     // initial sorting
        }
    }, {
        getData: function($defer, params) {
            var filteredData = $filter('filter')(users, $scope.filter);
            var orderedData = params.sorting() ?
                                $filter('orderBy')(filteredData, params.orderBy()) :
                                filteredData;

            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
        },
        $scope: $scope
    });

});

然后我的工厂服务是:

myApp.factory('userData', function($http, $log){
    return {
        getUsers: function(successcb){
            $http({method: 'GET', url: 'api/users'}).
                success(function(data, status, headers, config){
                    successcb(data);
                    $log.warn(data, status, headers, config);
                }).
                error(function(data, status, headers, config){
                    $log.warn(data, status, headers, config);
                });
        }
    }
});

我的HTML是这样的:

<div class="row">
    <div>
        <p>Filter: <input class="form-control" type="text" ng-model="filter.$" /></p>

        <table ng-table="tableParams" class="table">
            <tr ng-repeat="user in $data">
                <td data-title="'Name'" sortable="name">
                    {{user.name}}
                </td>
                <td data-title="'Age'" sortable="'age'">
                    {{user.age}}
                </td>
            </tr>
        </table>
    </div>
</div>

1 个答案:

答案 0 :(得分:4)

您需要在ajax完成后解析表$defer中的getData。如果您要将filteredData记录到控制台,它现在就是现在,它将是未定义的,因此无法切片。

尝试将userData.getUsers移至:

getData: function ($defer, params) {
     /* make ajax call */
    userData.getUsers(function(users) {
        /* now we have data to work with*/
        $scope.users = users;

        var filteredData = $filter('filter')(users, $scope.filter);
        var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : filteredData;
        /* and can resolve table promise  */
        $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));

    })

}