AngularJS HttpRequest



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

function studentController($scope,$https:) {
   var url="data.txt";
   $https:.get(url).success( function(response) {
      $scope.students = response; 
   });
}

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

Examples

data.txt
[
   {
      "Name" : "Mahesh Parashar",
      "RollNo" : 101,
      "Percentage" : "80%"
   },
   {
      "Name" : "Dinkar Kad",
      "RollNo" : 201,
      "Percentage" : "70%"
   },
   {
      "Name" : "Robert",
      "RollNo" : 191,
      "Percentage" : "75%"
   },
   {
      "Name" : "Julian Joe",
      "RollNo" : 111,
      "Percentage" : "77%"
   }
]
testAngularJS.htm
<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="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>
function studentController($scope,$https:) {
   var url="data.txt";
   $https:.get(url).success( function(response) {
      $scope.students = response;
   });
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

Output

To run this example, you need to deploy textAngularJS.htm, data.txt to a webserver. Open textAngularJS.htm using url of your server in a web browser. See the result.

AngularJS HTTPReqest
Advertisements