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>