With the /word
route handler in place, you can implement the AngularJS controller that accesses the list of words displayed in the table. Listing 29.17 implements tableController
in the AngularJS application Module
object.
The first few lines define the words array, which contains the data for the table as well as the contains
, limit
, skip
, and direction
values used in the $http GET
request to retrieve the set of words. The sortFields
array provides data to select which field to sort on.
The getWords()
function makes an $http GET
request to the /words
route and populates the $scope.words
array that is bound to the table data with the results. Notice that the limit
, skip
, sort
, direction
, and contains
fields are sent with the request to support sorting, paging, and filtering.
The find()
method reinitializes the skip
value and then calls getWords()
to perform a new search. The next()
and prev()
methods adjust the skip
value to page the results from the words database.
001 var app = angular.module('richApp', []);
002 app.controller('tableController', function($scope, $http) {
003 $scope.words = [];
004 $scope.contains = '';
005 $scope.limit = 5;
006 $scope.skip = 0;
007 $scope.skipEnd = 0;
008 $scope.sortFields = ['Word', 'First', 'Last', 'Length',
009 'Vowels', 'Consonants'];
010 $scope.sortField ="Word";
011 $scope.direction = "asc";
012 $scope.getWords = function(){
013 $http({url: '/words', method: "GET",
014 params:{ limit:$scope.limit,
015 skip:$scope.skip,
016 sort:$scope.sortField,
017 direction:$scope.direction,
018 contains:$scope.contains }})
019 .success(function(data, status, headers, config) {
020 $scope.words = data;
021 $scope.skipEnd = $scope.skip + $scope.words.length;
022 })
023 .error(function(data, status, headers, config) {
024 $scope.words = [];
025 $scope.skipEnd = $scope.skip + $scope.words.length;
026 });
027 };
028 $scope.find = function(){
029 $scope.skip = 0;
030 $scope.getWords();
031 };
032 $scope.next = function(){
033 if($scope.words.length == $scope.limit){
034 $scope.skip += parseInt($scope.limit);
035 $scope.getWords();
036 }
037 };
038 $scope.prev = function(){
039 if($scope.skip > 0){
040 if($scope.skip >= parseInt($scope.limit)){
041 $scope.skip -= parseInt($scope.limit);
042 } else{
043 $scope.skip = 0;
044 }
045 $scope.getWords();
046 }
047 };
048 $scope.getWords();
049 });