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,902
  • 4
  • 34
  • 64

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,393
  • 2
  • 15
  • 19