gpt4 book ai didi

angularjs - 我收到类型错误 : Cannot call method 'slice' of undefined when loading data from factory ng-Table AngularJS

转载 作者:行者123 更新时间:2023-12-02 09:06:02 25 4
gpt4 key购买 nike

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

类型错误:无法调用未定义的方法“切片” 在Object.$scope.tableParams.ngTableParams.getData (index.html:122:32)

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

我的 Controller 如下所示:

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>

最佳答案

ajax 完成后,您需要解析表 getData 中的 $defer。就目前情况而言,如果您要将 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()));

})

}

关于angularjs - 我收到类型错误 : Cannot call method 'slice' of undefined when loading data from factory ng-Table AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20115061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com