Popularni postovi

Monday, 7 July 2014

Search/Filter/Pagination with WebAPI and AngularJS

In Web API insert this:

  public IHttpActionResult GetKontakti(int page = 1,int itemsPerPage = 30, 
            string sortBy = "Naziv",bool reverse = false, string search = null)
        {
            String sort = sortBy + (reverse ? " descending" : "").ToString();

            var data = db.Kontakti.OrderBy(sort);
            
            // paging
            var usersPaged = data.Skip(((page - 1) * itemsPerPage)).Take(itemsPerPage);

            // json result
            var json = new
            {
                count = data.Count(),
                Kontakti = usersPaged
            };
            return Ok(json);
        }

Before this you need to add dependency:

 using System.Linq.Dynamic;   
This enables you to pass string in OrderBy function, otherwise you would have to write if for every column...


You can test this with url:
http://localhost:26264/api/kontakti?itemsPerPage=2&page=1&reverse=false&search=&sortBy=Naziv&totalItems=0

In JavaScript this code wil call this:



 function getKontakti() {
        kontaktiService.getkontakti(function (results) {

            $scope.kontakti = results.kontakti;
            $scope.pagingInfo.totalItems = results.count;
        }, $scope.pagingInfo)
    }   

  function inittable() {
            $scope.pagingInfo = {
                page: 1,
                itemsPerPage: 5,
                sortBy: 'Naziv',
                reverse: false,
                search: '',
                totalItems: 0
            };
         // You are watching here for sort event
            $scope.$on('ngGridEventSorted', function (event, sortInfo) {
                $scope.pagingInfo.sortBy = sortInfo.fields[0];
                if (sortInfo.directions[0] == 'asc') $scope.pagingInfo.reverse = false; else $scope.pagingInfo.reverse = true;
            });
            // Load data here because event sort runs MULTIPLE times
            $scope.$watch('pagingInfo', function () {
                loadData();
            }, true);

            $scope.search = function () {
                $scope.pagingInfo.page = 1;
                loadData();
            };
 
            $scope.sort = function (sortBy) {
                if (sortBy === $scope.pagingInfo.sortBy) {
                    $scope.pagingInfo.reverse = !$scope.pagingInfo.reverse;
                } else {
                    $scope.pagingInfo.sortBy = sortBy;
                    $scope.pagingInfo.reverse = false;
                }
                $scope.pagingInfo.page = 1;
                loadData();
            };
 
            $scope.selectPage = function (page) {
                $scope.pagingInfo.page = page;
                loadData();
            };
 
            function loadData() {
                
                getKontakti();
            }
 
            // initial table load
            loadData();
    }
    inittable();

Also you need this code to call in service part:

function getkontakti(callback, pagingInfo) {

            if (pagingInfo == undefined)
                $http.get(url).success(callback);
            else $http.get(url, { params: pagingInfo }).success(callback);
        }

HTML Data Table with pagination and sorting:

//ng-grid:
<div class="gridStyle" ng-grid="gridOptions"></div> 
//regular table:
<table class="table table-striped table-bordered table-hover table-condensed">
        <thead>
            <tr>
                <th><a href="" ng-click="sort('Naziv')">Naziv</a></th>
                <th><a href="" ng-click="sort('OpcinaID')">Opcina</a></th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="kontakt in kontakti">
                <td>{{kontakt.naziv}}</td>
                <td>{{kontakt.opcinaID}}</td>
            </tr>
        </tbody>
    </table>

    <pagination page="pagingInfo.page"
                total-items="pagingInfo.totalItems"
                items-per-page="pagingInfo.itemsPerPage"
                on-select-page="selectPage(page)"
                max-size="10"
                rotate="false"
                boundary-links="true"></pagination>

If you are using ng-grid you will have to add this to controller js file:


  $scope.gridOptions = {  
     data: 'kontakti',  
     showGroupPanel: true,  
     columnDefs: [{ field: 'id', displayName: 'Id', width: '20px' },  
           { field: 'naziv', displayName: 'Naziv:', width: '50px' },  
           { field: 'datumRodjenja', displayName: 'Datum rodjenja:', width: '130px' },  
           { field: 'email', displayName: 'Email:', width: '50px' },  
       { displayName: 'Options', cellTemplate: '<input type="button" ng-click="setScope(row.entity,\'edit\')" name="edit" value="Edit">&nbsp;<input type="button" ng-click="DeleteUser(row.entity.id)" name="delete" value="Delete">', width: '25%' }  
     ]  
   };  

Here is pagination in ng-grid way: http://plnkr.co/edit/50vJrs?p=preview

No comments:

Post a Comment