I'm attempting to implement infinite scrolling as documented here: https://material.angularjs.org/latest/demo/virtualRepeat
However, all the examples I've found use $http.get to request an external .json document. I want to use an existing JSON array stored in a scope retrieved by another function within the controller. To simplify things for testing purposes, I created a plunkr that only performs the basics.
Here's a working example I found using an external .json file: http://plnkr.co/edit/e32qVQ4ECZBleWq2Gb2O?p=preview
All I should need to do is replace the $http.get request code with my $scope.items, but I have been unsuccessful in my attempts. Here's my modified example that I've been working off of: http://plnkr.co/edit/S2k6pxJ2mZ7MQsILnmvS?p=preview
(function () {
'use strict';
angular
.module('infiniteScrolling', ['ngMaterial'])
.controller('AppCtrl', function ($timeout,$scope) {
$scope.items = [
{
"categoryId": "cat1",
"id": "pack0"
},
{
"categoryId": "cat1",
"id": "pack8"
},
{
"categoryId": "cat1",
"id": "pack9"
},
{
"categoryId": "cat1",
"id": "pack10"
},
{
"categoryId": "cat1",
"id": "pack11"
}
];
// In this example, we set up our model using a plain object.
// Using a class works too. All that matters is that we implement
// getItemAtIndex and getLength.
var vm = this;
vm.infiniteItems = {
numLoaded_: 0,
toLoad_: 0,
// Required.
getItemAtIndex: function (index) {
if (index > this.numLoaded_) {
this.fetchMoreItems_();
return null;
}
return this.items[index];
},
// Required.
getLength: function () {
return this.numLoaded_ + 5;
},
fetchMoreItems_: function ($scope, index) {
if (this.toLoad_ < index) {
this.toLoad_ += 5;
$scope.items.then(angular.bind(this, function (obj) {
this.items = this.items.concat(obj.data);
this.numLoaded_ = this.toLoad_;
}));
}
}
};
});
})();
http://plnkr.co/edit/GUvhluPx3bS2XUSjFHvN?p=preview
Since you are trying to replace a $http.get
call which returns a promise you can just replace that with a $timeout
(since this also returns a promise and will trigger an $apply
). Only other caveat then is the object the $timeout returns doesn't have a data property (this is only a feature of the httppromise since it has http status etc.) so I had to also change obj.data
to obj