I stumbled upon this AngularJS script while searching for some samples, but I'm having trouble understanding the angular module and directive aspects of the code. However, I did manage to modify the loadMore() function to fetch a JSON resource from my RESTful API and it's working well with the infinite scroll feature. Could someone kindly explain how this all works? I've just started learning and experimenting with AngularJS in my free time over the past week...
Original source: http://jsfiddle.net/vojtajina/U7Bz9/
function Main($scope) {
$scope.items = [];
var counter = 0;
$scope.loadMore = function() {
for (var i = 0; i < 5; i++) {
$scope.items.push({id: counter});
counter += 10;
}
};
$scope.loadMore();
}
angular.module('scroll', []).directive('whenScrolled', function() {
return function(scope, elm, attr) {
var raw = elm[0];
elm.bind('scroll', function() {
if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
scope.$apply(attr.whenScrolled);
}
});
};
});
My modified version:
function Main($scope, $http) {
$scope.phones = [];
$scope.loadMore = function() {
$http.get('http://www.somewhere.com/api/phones').success(function(data) {
if($scope.phones.length > 0) {
$scope.phones = $scope.phones.concat(data);
}
else {
$scope.phones = data;
}
});
};
$scope.loadMore();
}