Scenario: – How to fetch JSON data from backend into User Interface (UI) of application using Angular JS?
Solution:-
We have divided our solution approach into 2 parts; in part-1, tutorial we would fetch the data in a straight flow, without thinking about the framework level things.
Flow:-
Code:-
JS File
//Creat app module
var app = angular.module('myApp',[])
//Creating the controller constructor
app.controller('familyCtrl',function($scope,$http){
//Calling the get method of service
$http.get("data/family.json").then(function(response){
$scope.myData = response.data;
});
});
html file
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/controllerRead.js"></script>
<link rel="stylesheet" type="text/css" href="css/family.css">
</head>
<body>
<div ng-controller="familyCtrl">
<p>Reading JSON data using AngularJS Service component</p>
<ul>
<li ng-repeat="x in myData.family">
{{ x.age + ', ' + x.role }}
</li>
<li>
House No = {{myData.house[0].no}}
</li>
<li>
Income = {{myData.income}}
</li>
</ul>
</div>
</body>
</html>
Explanation:-
JS File:- it contains the business logic, which uses the get method of the service ($http), to fetch data from JSON, on success it binds data to scope (myData).
JSON File:-It consists of our JSON data. Few points to know for beginners in JSON
- JSON (Java script object Notation), to store information in organized manner. Everything is in the form of object, as name –value pairs.
- Read from the official JSON website for basics
- After creating any JSON file, it’s better to validate it before using in project
HTML File:-Consists of ng-app (bootstrap angular), ng-controller(using this directive to link to controller – controllerRead.js), ng-repeat (to repeat it for all the values of json element) and lastly we use the scope to display the fetched data from JSON.
One reply on “Reading JSON data in Angular JS (Part-1)”
very helpful