In order to read data from the server, AngularJS provides $http control. A database call is made by the server to get the desired records. The data has to be in JSON format in case of AngularJS.
There are various ways in which we can send AJAX requests in AngularJS. The methods are.
A point to note is that so far we have covered only the $http service (both normal AJAX and JSONP), but we need to know about some more things before we get started with AJAX in AngularJS. The REST API is not required to start learning AJAX.
The most convenient way of sending AJAX calls to your web server is by using the $http service. It should be remembered that AJAX calls cannot be sent to a domain which is different from the domain from which the HTML page is loaded. For example, if the HTML page was from abc.com then in order to make calls by that HTML page, the URL's have to be in abc.com domain only.
After the data is ready, the $http service can be used in the following manner to get data from the server.
The given file data.txt contains records of students. $http service makes an AJAX call and sets response to its property students.
[ { "Name" : "Ramesh Singh", "Age" : 25, "Salary" : "20000" }, { "Name" : "Harish sharma ", "Age" : 22, "Salary" : "22000" }, { "Name" : "Neha ", "Age" : 40, "Salary" : "67000" }, { "Name" : "Jomash", "Age" : 21, "Salary" : "55000" }
<!DOCTYPE html> <html> <head> <title>Angular JS Includes Example</title> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "" ng-controller = "employeeController"> <table> <tr> <th>Name</th> <th>Age</th> <th>Salary</th> </tr> <tr ng-repeat = "employee in employees"> <td>{{ employee.Name }}</td> <td>{{ employee.Age }}</td> <td>{{ employee.Salary }}</td> </tr> </table> </div> <script> function employeeController($scope,$http) { var url = "data.txt"; $http.get(url).success( function(response) { $scope.employees = response; }); } </script> <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
There are several shortcut methods in case of $http service. Some of them are listed below.
As a response from the server, we get an object with the following properties
The data obtained from the response should be in the JSON format. It is one of the best ways of transporting data, and is convenient to use within AngularJS or any other JavaScript.