Read Json and display the records using AngularJS Expression

Rajnilari2015
Posted by in AngularJS category on for Beginner level | Points: 250 | Views : 1877 red flag
Rating: 5 out of 5  
 2 vote(s)

AngularJS is a MV* Javascript framework developed by Google. It is widely use across the industry.In this article, we will read a JSON file and display the information about the same using AngularJS Expression.


 Download source code for Read Json and display the records using AngularJS Expression

Introduction

AngularJS is a MV* JavaScript framework developed by Google. It is widely use across the industry.In this article, we will read a JSON file and display the information about the same using AngularJS Expression.

What is an Expression in AngularJS?

Well, though we made the question specific to AngularJS but an expression is any normal expression written in any programming language. e.g.

a+b

is an expression in JavaScript.

If we have to write the same in AngularJS way it will be

{ { a + b }}

that means to write the statement inside a double brace

Expressions are basically use to bind the data from the controller to the view (which is the HTML).

Using the code

Let us first create the student.json

[{
    "id": 1,
    "name": "Niladri Biswas",
    "gender":"Male",
    "photo":"images/1.jpg",
    "english": 80,
    "maths": 75
  }, {
   "id": 2,
    "name": "Arina Biswas",
    "gender":"Female",
    "photo":"images/2.jpg",
   "english": 70,
   "maths": 69
  }, {
   "id": 3,
     "name": "Rajlaxmi Biswas",
     "gender":"Female",
     "photo":"images/3.jpg",
   "english": 98,
   "maths": 100
  },
  {
   "id": 4,
     "name": "RNA Team",
     "gender":"Male",
     "photo":"images/4.jpg",
   "english": 88,
   "maths": 70
  }]

It is a simple Json structure with the properties of id,name,gender,photo,english and maths. Once we open the .zip file, it will be inside the images folder

Now let us look into the studentController.js

//creating an application module
var studentAppModule = angular.module("studentApp", []);

//The below code will read the data from student.json file and will pass to the $scope variable 
studentAppModule.controller("StudentCtrl", function($scope, $http){    
            $http.get('data/student.json') //reading the student.json file
            
                .success (function(data){
                        $scope.students = data; // binding the data to the $scope variable
                    })
                .error(function(data, status) {
                        console.error('failure loading the student record', status, data);
                        $scope.students = { }; //return blank record if something goes wrong
                });
    } 
);//end controller

The code pattern is a typical MVC one. At first we are creating the studentAppModule.It is an Application Module that is use to initialize the application with controller which is StudentCtrl in our case.

Next we have created a controller module StudentCtrl by using the Application Module.controller function (i.e. studentAppModule.controller).

For reading data from the Json file, we are using $http.get function where in the success case we are setting the data to the $scope.students variable and if anything goes wrong while reading the data, we are setting the $scope.students = { } as empty.

The $scope.students variable acts as a glue for carrying the data from the controller to the view (i.e. html part).

Now once the controller is ready, it's time to bind the data to the view. So let's create the below html

<!DOCTYPE html>
<html>
<head>
  <script data-require="angular.js@1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js">
  </script> 
 <script src="studentController.js"></script>
</head>

<body ng-app="studentApp">
        <div align="center"><b><u><font size="8px">Student Information</font></u></b></div>
        <div ng-controller="StudentCtrl" align="center">  
            <table border="1">
                <tr>
                      
                      <th>Name</th> 
                      <th>Photo</th>                 
                      <th>Gender</th>
                      <th>English</th>
                      <th>Maths</th>
                      <th>Combined Marks in English and Maths</th>                      
                </tr>
                <tr ng-repeat="student in students">
                         
                      <td><span>{{student.name}}</span></td>    
                      <td><span><img src={{student.photo}} width="100px" height="100px" /></span></td>                 
                      <td><span>{{student.gender}}</span></td>
                      <td><span>{{student.english}}</span></td>
                      <td><span>{{student.maths}}</span></td> 
                      <td><span>{{ (student.english)--(student.maths) }}</span></td> 
                </tr>             
            </table>
        </div>        
    </body>
</html>

At first we are loading the AngularJS and the studentController.js files. Then we are defining the Application Module(studentApp) inside the body by using the ng-app.

ng-app is an AngularJS directive which indicates the start of the AngularJS application.Then by using the ng-controller, we have attached the controller (StudentCtrl) to the view (html).Now since we have multiple records to loop through, we need to use the ng-repeat directive which is basically a kind of loop in AngularJS parlance.

Once we loop through the student records, then by using expression, we have bind the properties from controller to the view. Observe the way we have calculated the Combined Marks in English and Maths using the double negation

{{ (student.english)--(student.maths) }}

It is nothing new since a -- b is equals to a+b.Since in JavaScript, a '+' is treated as a concatenation operator by default, henceforth we need to convert the string to an integer and perform an addition. This is just another alternative of performing the same.

The result at this stage will be

Now suppose we want to have the total of all the values of the column Combined Marks in English and Maths which is 650.In this case, let us write a function and invoke the same from the expression as under

//calculate the total marks of all the students
 $scope.getTotalMarks = function(key) {
                    var total = 0;
                    angular.forEach($scope.students, function(record) {
                    total += record[key];
                });
                return total;
            };//end function getTotalMarks

We are using the angular.forEach function that iterates through the collection for the key specified.

Now let us look into the Html part

<tr>
    <td colspan="5">Total Marks for all students:</td>                      
    <td>{{   ( getTotalMarks('english') * 1 )  + ( getTotalMarks('maths') * 1 )  }}</td>
</tr>

This is just another way of evaluating an expression (earlier we say the double negation technique) for finding the sum.Here in the first case we are passing english as the key and then maths and finally get the total.The output is as under

References

Mr. Sheo Narayan has written a great series of article on AngularJS How to Tips & Tricks at Techfunda. It's a must read for all of us which will help a lot.

Apart from that, we can follow AngularJS Developer Guide from the AngularJS official site.

Conclusion

Hope this will be helpful. Thanks for reading. Zipped file is attached herewith.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Posted by: Debendra256 on: 3/29/2016 | Points: 25
Nice one sir....
Posted by: Nagarajasia on: 4/4/2016 | Points: 25
Superb...

Login to post response

Comment using Facebook(Author doesn't get notification)