Citizen SP Citizen SP - 4 months ago 9
AngularJS Question

remember search query to use in function

I'm using Angularjs with the dirPagination plugin to connect with an Web API. This seems to work fine. I added a search function, to do a server side search:

$scope.searchChanged = function () {

if ($scope.searchFor.length == 0) {
$scope.calculatedValue = 'e';
} else {
vm.getData(vm.pageno, vm.getSearch($scope.searchFor));
}
}

vm.getSearch = function (query) {

if (query == undefined) {
query = 'tech';
} else {
query = query;
}
return query;
}


See Plnkr for the full code
If I start searching (e.g. sales) the API returns results and the paging is correct, the get request is:

/api/students/?category=sales&begin=1&pageSize=10


But if you want to go to another page number, the get request to the server is:

/api/students/?category=tech&begin=2&pageSize=10


How can the view remember the query 'sales', so that the paging and results are correct?

Answer

You are making a common mistake here: You don't need to pass in variable from the view if you are already using a scope variable.

Changing to this would be much less error prone

        // change this to var getSearch or function getSearch if you don't need it on the view anymore
        vm.getSearch = function () {
            var query = vm.searchFor;
            // you should only use vm, change ng-model to data.searchFor

            if (query == undefined) {
                query = 'tech';
            }

            return query;
        }


        vm.getData = function () {
            vm.users = [];

            $http.get("/api/students/?category=" + vm.getSearch() + "&begin=" + vm.pageno + "&pageSize=" + vm.itemsPerPage).success(function (response) {
                vm.users = response.data;
                vm.total_count = response.total_count;
            });
        };