$http is
a service for reading data from web services (data servers). The AngularJS
$http service makes a request to the server, and returns a response.
Today I am going to show a very simple way to load
external JSON file in AngularJS 1 :
Sample json file :
data.json
{
"Person":
[
{
"Name":
"Swati",
"Location":
"Office"
},
{
"Name":
"John",
"Location":
"Home"
}
]
}
index.html
<!DOCTYPE
html>
<html>
<head>
<meta
http-equiv="Content-Type"
content="text/html; charset="
utf-8" />
<meta
name="viewport" initial-scale="1.0"
content="width=device-width"
user-scalable="yes" />
<title>Load
External JSON</title>
<script
src="libs/angular.min.js"></script>
<script
src="controller/loadController.js"
type="text/javascript"></script>
</head>
<body
ng-app="loadJsonPrj"
ng-controller="LoadJsonCtrl">
<button
type="button" ng-click="loadJson()">
Load External JSON </button>
<ul>
<li
ng-repeat="data in getResponse">{{
data.Name+ ', ' + data.Location}}
</li>
</ul>
</body>
</html>
loadController.js
var
myApp = angular.module('loadJsonPrj', []);
function
LoadJsonCtrl($scope, $http) {
$scope.loadJson
= function() {
$http.get('data.json').then(function(response)
{
$scope.getResponse
= response.data.Person;
console.log($scope.getResponse);
},
function(response) {
$scope.getResponse
= "Something went wrong";
});
}
}
myApp.controller('LoadJsonCtrl',
LoadJsonCtrl);
Output:
Happy Coading :)
No comments:
Post a Comment