Within the service:
appRoot.factory('ProgramsResource', function ($resource) {
return $resource('Home/Program', {}, { Program: { method: 'get', isArray: false } })
});
Inside the controller:
appRoot.controller('ProgramCtrl', function ($scope, ProgramsResource) {
$scope.searchPrograms = function () {
$scope.Programs = ProgramsResource.get(
{
Name: $scope.searchProgramName,
});
};
$scope.SortBy = "Name";
$scope.searchPrograms();
//The code below is intended to run only after searchPrograms() is completed
$scope.TotalItems = $scope.Programs.TotalItems;
$scope.ItemsPerPage = $scope.Programs.ItemsPerPage;
});
The function searchPrograms(); is used for fetching data from the server. The lines of code following $scope.searchPrograms(); should be executed afterwards:
$scope.TotalItems = $scope.Programs.TotalItems;
$scope.ItemsPerPage = $scope.Programs.ItemsPerPage;
However, instead of waiting for searchPrograms() to finish its operation, the code beneath it is getting executed. This is a common behavior in JavaScript where it does not pause for AJAX calls to complete before moving on to the next lines. To ensure that certain code executes only after an AJAX call is finished, callbacks are used in JavaScript and promises are commonly employed in AngularJS for this purpose.
I came across an insightful article about Angular promises but am struggling to understand how I can implement promises in my specific scenario.