AngularJS provides a $http service for reading data and remote servers. It is used to retrieve the desired records from a server.
AngularJS requires data in JSON format. Once the data is ready, $http gets the data form server in the following manner:
function employeeController($scope,$http) {
r url = "data.txt";
$http.get(url).success( function(response) {
$scope.employees = response;
});
Here the file “data.txt” is employee’s records. $http service makes an AJAX call and sets response to its property employees. This model is used to draw tables in HTML.
AngularJS AJAX Example
testAngularJS.htm
<!DOCTYPE html>
<html>
<head>
<title>Angular JS Includes</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>
Here the file data.txt contains the employee’s record.
“data.txt” (employee’s data in JSON format)
[
{
"Name" : "Mahesh Sharma",
"Age" : 25,
"Salary" : "20000"
},
{
"Name" : "Rohan Malik",
"Age" : 20,
"Salary" : "22000"
},
{
"Name" : "Robert Petro",
"Age" : 45,
"Salary" : "67000"
},
{
"Name" : "Jullia Roberts",
"Age" : 21,
"Salary" : "55000"
}
To execute the above example, you have to deploy testAngularJS.htm and data.txt file to a web server.
Open the file testAngularJS.htm using the URL of your server in a web browser and see the result.
Output:
The result would look like this:
Table:
Name | Age | Salary |
---|---|---|
Mahesh Sharma | 25 | 20000 |
Rohan Malik | 20 | 22000 |
Robert Petro | 45 | 67000 |
Jullia Roberts | 21 | 55000 |
HTTP Service Methods
There are several shortcut methods of calling the $http service. In the above example, .get method of the $http service is used. Following are several other shortcut methods:
- .delete()
- .get()
- .head()
- .jsonp()
- .patch()
- .post()
- .put()
Properties
The response from the server is an object with these properties:
- .config the object used to generate the request.
- .data a string, or an object, carrying the response from the server.
- .headers a function to use to get header information.
- .status a number defining the HTTP status.
- .statusText a string defining the HTTP status.
Leave a Reply