Making an AJAX call in Angular.js

As we all know AJAX call is used to process an asynchronous request initiated by the browser. The result of AJAX call is not a page transition directly but the action takes place. You can submit forms and datas on a page through AJAX but the page will not refresh as it does in a traditional HTML form submission. In Angular.js we are making an AJAX call to create a service that returns a promise to the returned data, and call that in your controller and handle the promise to load your $scope property. An example is shown below for understanding it better.

The service:


module.factory('myService',function($http) {

return {

getFoos:function() {

//return the promise directly.

return $http.get('/foos')

.then(function(result) {

//resolve the promise as the data

return result.data;

});

}

}

});


The controller:

The promise’s then method is handled and get the data. Then sets the $scope property and do what you need.


module.controller('MyCtrl',function($scope, myService) {

myService.getFoos().then(function(foos) {

$scope.foos = foos;

});

});