blog

Home / DeveloperSection / Blogs / Working with Ajax in AngularJs

Working with Ajax in AngularJs

Anonymous User4743 24-Mar-2015

Hi everyone in this blog I’m explaining about Ajax in AngularJs

Introduction:

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

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

Here data.txt contains the student records. $http service makes an Ajax call and set response to its property student. “Students” model can be used to be used to draw tables in the html.

Example:

Data.txt:
[
{
"Name" : "Kamlakar Singh",
"RollNo" : 1027,
"Percentage" : "73%"
},
{
"Name" : "Pawan Shukla",
"RollNo" : 1024,
"Percentage" : "70%"
},
{
"Name" : "Rohit",
"RollNo" : 1006,
"Percentage" : "75%"
},
{
"Name" : "Haider",
"RollNo" : 1002,
"Percentage" : "75%"
}
]

 

Angularjs.html
<html>
<head>
<title>Angular JS Includes</title>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<style>
table, th , td {
  border: 1pxsolidgrey;
  border-collapse: collapse;
  padding: 5px;
}
tabletr:nth-child(odd) {
  background-color: #f2f2f2;
}
tabletr:nth-child(even) {
  background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<divng-app="mainApp"ng-controller="studentController">
<table>
   <tr>
      <th>Name</th>
      <th>Roll No</th>
      <th>Percentage</th>
   </tr>
   <trng-repeat="student in students">
      <td>{{ student.Name }}</td>
      <td>{{ student.RollNo }}</td>
      <td>{{ student.Percentage }}</td>
   </tr>
</table>
</div>
<script>
    var mainApp = angular.module("mainApp", []);
 
    mainApp.controller('studentController', function ($scope) {
        var url = "data.txt";
        console.log(url);
        $http.get(url).success(function (response) {
            console.log("Yes");
            $scope.students = response;
        });
        console.log("No");
    });
</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.

Working with Ajax in AngularJs


I am a content writter !

Leave Comment

Comments

Liked By