Home  >  Angular JS

Reading JSON by AngularJS Service

January 07, 2015
In AngularJS we can access external data by using angular service. It is called a service or AngularJS service or $http service in AngularJS. An angularJS service code reads data in JSON format. as below.
 <div ng-app="" ng-controller="addressController"> 
   <ul> 
    <li ng-repeat="x in addlist">
       {{ x.Name + ',' + x.City + ',' + x.Country}} <br><br>
    </li>
   </ul>
</div> 
JSON format is lightweight data-interchange format. In our application we have used a particular service, it is called '$http service' that communicates between http server and our application.

Example

In example we create two file one file is HTML file and another is json.js file.
 <!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
 <div ng-app="" ng-controller="addressController"> 
    <ul> 
    <li ng-repeat="x in addlist">
       {{ x.Name + ',' + x.City + ',' + x.Country}} <br><br>
  </li>
</ul>
</div>
<script>
function addressController($scope,$http) {
  $http.get("json.js")
  .success(function(response)
    {
	  $scope.addlist = response;
	}
  );
}
</script>
</body>
</html> 
Find the file that will return JSON.
json.js
[
{
"Name" : "Amit",
"City" : "Mumbai",
"Country" : "India"
},
{
"Name" : "Ram Singh",
"City" : "Ghaziabad",
"Country" : "India"
},
{
"Name" : "Ankit Pandey",
"City" : "New Delhi",
"Country" : "India"
},
{
"Name" : "Subhash",
"City" : "Noida",
"Country" : "India"
},
{
"Name" : "Jurfuddin",
"City" : "Kerla",
"Country" : "India"
}
] 

Output

Reading JSON  by AngularJS Service
In this example, AngularJS $http is a core service for reading data from web servers and $http.get(url) is the function to use for reading server data. In HTML program we are define ng-app and ng-controller directive inside a <div>. The AngularJS application is defined by ng-app. The ng-controller defines addressController function. It is a standard JavaScript object constructor. AngularJS will invoke addressController with a $scope and $http object. $scope is the application object and $http is an XMLHttpRequest object for requesting external data. The $http.get() reads static JSON data from json.js file. If success, the controller creates a property (addlist) in the scope, with JSON data from the server. The ng-repeat directive repeats an HTML element and gives address list in application.
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us