Monday, 25 May 2015

Use of $http

Angular JS provides $http control which works as a service to read data from the server. Server can make a database call to get the records. Angular JS needs data in JSON format. Once data is ready, $http can be used to get the data from server.

I will explain it with a small example:-


data.txt:-
[
{
"Name" : "Anik Acharjee",
"RollNo" : 101,
"Percentage" : "80%"
},
{
"Name" : "Rahul Rajput",
"RollNo" : 201,
"Percentage" : "70%"
},
{
"Name" : "Ram Sharma",
"RollNo" : 301,
"Percentage" : "75%"
},
{
"Name" : "Sachin Gupta",
"RollNo" : 401,
"Percentage" : "77%"
}
]


main.html:-
<html>
<head>
<title>Angular JS Includes</title>
<script src="angular.js"></script>
<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 $http Application</h2>
<div ng-app="mainApp" ng-controller="studentController">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat="student in students">
<td>{{ student.Name }}</td>
<td>{{ student.RollNo }}</td>
<td>{{ student.Percentage }}</td>
</tr>
</table>
</div>
<script src="controller.js"></script>
</body>
</html>


app.js:-
var mainApp = angular.module("mainApp", []);


controller.js:-
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope,$http) {
var url="data.txt";
$http.get(url).success( function(response) {
$scope.students = response;
});
});


Screenshot:-





Explanation:-

Here, data.txt contains all the student records. "$http" service makes an ajax call and set response to its property students. "students" model can be used to draw tables in the html.

No comments:

Post a Comment