ASP.Net MVC Infinite Scrolling With Angularjs

Today we are going to implement infinite/unlimited scrolling using AngularJS in MVC application.

Infinite/unlimited scroll worked while we scroll down the web page it’ll automatically load next paged data. Facebook has this type of News feed loading.

Let’s Get Started:

Let’s create a view with directive ‘when-scrolled’. AngularJS ‘when-scrolled’ directive is to implement infinite scrolling, which is suppose to detect the div scroll.

when-scrolled="loadData(1)"

Here ‘loadData(1)’ callback function will get called while div/page is scrolled. In this method we have passed parameter value ‘1’ to detect, is it default data load or scroll load call.

$scope.loadData = function (IsPaging) {}

This is where we passed the parameter in our ngController method.

Finally the View:

<div class="widget-content content_scroll" when-scrolled="loadData(1)">
    <table class="table table-striped table-bordered table-hover table-checkable datatable">
        <thead>
            <tr>
                <th>Office ID</th>
                <th>Office Code</th>
                <th>Office Name</th>
                <th>Is Active</th>
                <th>Create Date</th>
                <th>Create By</th>
                <th>Edit Date</th>
                <th>Edit By</th>
                <th>Status</th>
            </tr>
        </thead>

        <tbody>
            <tr ng-repeat="dataModel in ListOffice">
                <td>{{dataModel.OfficeID}}</td>
                <td>{{dataModel.OfficeCode}}</td>
                <td>{{dataModel.OfficeName}}</td>
                <td>{{dataModel.IsActive}}</td>
                <td>{{dataModel.CreateDate|date:"MM/dd/yyyy 'at' h:mma"}}</td>
                <td>{{dataModel.CreateBy}}</td>
                <td>{{dataModel.EditDate|date:"MM/dd/yyyy 'at' h:mma"}}</td>
                <td>{{dataModel.EditBy}}</td>
                <td>
                    <span class="label label-warning">
                        <a href="javascript:void(0);" class="bs-tooltip" title="Edit" ng-click="getOffice(dataModel)">
                            <i class="icon-pencil"></i>
                        </a>
                    </span>
                    <span class="label label-danger">
                        <a href="javascript:void(0);" class="bs-tooltip" title="Delete" ng-click="deleteOffice(dataModel)">
                            <i class="icon-trash"></i>
                        </a>
                    </span>
                </td>
            </tr>
        </tbody>
    </table>
    <div class="loadmore">
        <div ng-show="loaderMore" ng-class="result">
            <img src="~/Areas/Crm/Content/img/ng-loader.gif" />{{LoadMessage}}
        </div>
        <div ng-show="scrollended" ng-class="result">
            {{LoadMessage}}
        </div>
    </div>
</div>

We have declare directive ‘when-scrolled’ in our view, now we have to add directive in our module. In this app which is:

angular.module('uCRM_App', [])

The directive: This will detect the scroll position of page/div.

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

In out controller method we have pushed data into the array in scope to update the view.

for (model in data) {
    $scope.ListOffice.push(data[model]);
}

As we know AngularJS will update the view when scope is changed/update.

Finally the Script:

angular.module('uCRM_App', [])

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

.controller('OfficeController', function ($scope, $http) {

    $scope.loaderMore = false;
    $scope.scrollended = false;

    var IsPaging = 0;
    var UserID = 1;
    var page = 1;
    var PageSize = 20;
    var inCallback = false;
    var totalData = 0;

    //******=========Get All Data with Paging=========******
    $scope.loadData = function (IsPaging) {
        var geturl = '/Crm/api/Office/Get/';
        if (IsPaging === 1) {
            //debugger;
            IsPaging = 1;
            if (page > -1 && !inCallback) {
                inCallback = true;
                page++;

                $scope.loaderMore = true;
                $scope.LoadMessage = ' Loading page ' + page + ' of ' + PageSize + ' data...';
                $scope.result = "color-green";

                $http({
                    method: 'GET',
                    url: geturl + UserID + '/' + page + '/' + PageSize + '/' + IsPaging,
                })
                .success(function (data) {
                    totalData = data.length;
                    if (totalData === 0) {
                        $scope.loaderMore = false;
                        $scope.scrollended = true;
                        $scope.LoadMessage = 'No more data...!';
                        $scope.result = "color-red";

                        Command: toastr["warning"]("No more data...!");

                        inCallback = false;
                        page = -1;
                    }
                    else {
                        for (model in data) {
                            $scope.ListOffice.push(data[model]);
                        }
                        $scope.loaderMore = false;
                        inCallback = false;
                    }

                }).error(function (error) {
                    alert('Error Loading..');
                })
            }
        }//unlimited load data while scroll
        else {
            //debugger;
            IsPaging = 0; $scope.loaderMore = true;
            $scope.LoadMessage = ' Loading page ' + page + ' of ' + PageSize + ' data...';
            $scope.result = "color-green";

            $http({
                method: 'GET',
                url: geturl + UserID + '/' + page + '/' + PageSize + '/' + IsPaging,
            }).
            success(function (data) {
                $scope.ListOffice = data;
                $scope.loaderMore = false;
            }).
            error(function () {
                $scope.message = 'Unexpected Error while loading data!!';
                console.log($scope.message);
            });
        }//default load data while pageload

    };
    $scope.loadData();
});

Output:

sc

Happy Coding 🙂

Author:

Since March 2011, have 4 years of extensive hands on experience of software development.

7 thoughts on “ASP.Net MVC Infinite Scrolling With Angularjs”

Leave a Reply to VINAY GUPTA Cancel reply

Your email address will not be published. Required fields are marked *