2

I'm building a simple app that loads a json file and presents the content onto the screen and enables the user to scroll through pages using a simple pagination mechanism. I read here and tried to implement a dynamic retrieval of data using a real json hosted online using a dedicated service. The data loads fine but I'm getting an error: Cannot read property 'slice' of undefined.

JSfiddle here

The code: Html:

<div ng-controller="MyCtrl">
  <ul>
    <li ng-repeat="item in catalogData | startFrom:currentPage*pageSize | limitTo:pageSize">
      {{item}}
    </li>
  </ul>
  <button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
    Previous
  </button>
  {{currentPage+1}}/{{numberOfPages()}}
  <button ng-disabled="currentPage >= data.length/pageSize - 1" ng-click="currentPage=currentPage+1">
    Next
  </button>
</div>

Controller:

function MyCtrl($scope, dataService) {
  $scope.currentPage = 0;
  $scope.pageSize = 4;

  dataService.getData().then(function(data) {
    $scope.catalogData = data;
    $scope.numberOfPages = function() {
      return Math.ceil($scope.catalogData.length / $scope.pageSize);
    };
  });
}

Get data service:

app.service("dataService", function($http) {
  this.getData = function() {
    return $http({
      method: 'GET',
      url: 'https://api.myjson.com/bins/llzg3',
    }).then(function(data) {
      return data.data;
    });
  };
});

The filter:

app.filter('startFrom', function() {
  return function(input, start) {
    start = +start; //parse to int
    return input.slice(start);
  }
});
Alex
  • 1,982
  • 4
  • 37
  • 70
  • Not duplicate since they use a static array of data, and i load the data from the net, hence dynamic. – Alex Jul 15 '17 at 11:02
  • you are just passing one parameter to the filter `startFrom:currentPage*pageSize` <-- This is just one parameter. The Start Pârameter will be empty, then the return will be null and I supose the method will not be detected properly. You must give the positions to the `slice()` method as integers https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/slice – Alejandro Teixeira Muñoz Jul 15 '17 at 11:03

1 Answers1

1

When you're loading data from service and applying filter on it make sure you're defining that scope variable first. Because if you not then it'll take undefined until your data is available. Just adding following line of code in your controller will remove the error on console. Everything else executes the same as before:

$scope.catalogData = [];

I've forked to your version of jsfiddle, here's link for updated: http://jsfiddle.net/vrs8fv2e/1/

Shantanu
  • 3,483
  • 2
  • 17
  • 20