Ajax in AngularJS
AngularJS is terrific for client-side web programming, especially for SPA. However, it is no use without the data from the server-side. Ajax is a great tool for retrieving and sending data between the client-side and the server-side. Using ajax in angularJS is easy.
$http is the method or a built-in service in angularJS for making ajax calls. The example codes are as follows:
Or you can also write ajax in another way:
This works if you put $http
service in your Controller file. However, if you make the ajax call in your custom defined Services, then things will be different because of the asynchronous nature of ajax.
Returning data from service to controller in angularJS can be hard at first sight, because the returned data is no longer being visible (being undefined) when the controller begins use it. There are three solutions to the above mentioned problem:
- Utilizing the $q service
Then in the controller file, the returned promise can be used by then() method:
- Utilizing a callback function
The controller code for this second solution is shown below:
- Utilizing the $resource service
For this solution, what you need to do is two steps:
- Include the ‘angular-resource.min.js’ in the html file
- Inject the module dependency to the module creation js file like follows:
3.Create the $resource service in the service js file:
4.Inject the $resource service into the controller js file: