I get TypeError: I can not call the "slice" method undefined when loading data from factory ng-Table AngularJS

I am new to AngularJS and stuck in displaying data when using ng-Table coming from a service. I get an error

TypeError: it is not possible to call the 'slice' method from undefined in Object. $ scope.tableParams.ngTableParams.getData (index.html: 122: 32)

When I hardcoded the values ​​of json data, it works fine. I think the data from the factory contains more than just json data, so the slicing problem.

My controller is as follows:

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 }); }); 

Then my factory service is like this:

 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); }); } } }); 

My HTML is:

 <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> 
+6
source share
1 answer

You need to solve $defer in the getData table after ajax completes. Since it stands right now, if you have to log into the filteredData system for the console, it will be undefined, so it cannot be sliced.

Try moving userData.getUsers to:

 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())); }) } 
+4
source

Source: https://habr.com/ru/post/958540/


All Articles