Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this Sample AngularJS Infinite Scroll work

Tags:

I have found this sample AngularJS script when I was searching for some, but then I can't seem to get my head around the angular module and directive part of the code. Though I have managed to edit the loadMore() function to retrieve a json resource from my ReSTful API and it works great with the infinite scroll, can someone please give an explanation on how this works, I would really appreciate it. I have just barely started reading and trying AngularJS for the past week during my spare time...

Original from fiddle (A BIG Thank You to the original Author): 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);
            }
        });
    };
});

Modified by me:

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();
}