AngularJS AJAX
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:
Syntax:
function employeeController($scope,$http) {
var 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
1)testAngularJS.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 = "angular.min.js"></script>
</body>
</html>
2) data.text
Here the file data.txt contains the employee's record.
"data.txt" (employee's data in JSON format)
[
{
"Name" : "Prasad",
"Age" : 35,
"Salary" : "200000"
},
{
"Name" : "Ramesh",
"Age" : 20,
"Salary" : "22000"
},
{
"Name" : "Saradhi",
"Age" : 45,
"Salary" : "67000"
},
{
"Name" : "Ranesh",
"Age" : 21,
"Salary" : "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.
For
More Explanation
&
Online Classes
More Explanation
&
Online Classes
Contact Us:
+919885348743
+919885348743