AngularJS Animations

Animations are fancy movements and affects added to HTML elements in order to enhance visual appeal of the application. Usually JavaScript, JQuery and JQuery UI libraries are used to add animations to webpages. CSS3 also contains built-in animation capabilities. However, this article focuses on AngularJS Animations.

Before you could use AngularJS Animations, you have to perform following steps.

  • Add a reference to angular-animate.js libarary located at google CDN. The link to the library is “http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js”
  • Add the “ngAnimate” directive to the body of your application. In case if you have a named application, you can add this directive as dependency to the module.
  • Finally, use animations functions to perform different animations.

Take a look at the following example to see how AngularJS animations work.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"></script>
    
    <style>
    
        .circle-div {
          border: 1px solid black;
            width: 200px;
            height: 200px;
            border-radius: 100%;
            background: pink;
          margin-top: 10px;
          padding: 10px;
        }

        .sample-transition {
          transition: all linear 1.0s;
        }
        .sample-transition.ng-hide {
          opacity: 0;
        }

    </style>
    
</head>
<body ng-app="ngAnimate">
    
<div ng-init="checked = true">
  <p>
    <input type="checkbox" ng-model="checked" />
    Circle Visible?
  </p>
  <div class="circle-div sample-transition" ng-show="checked">
   
  </div>
</div>


</body>
</html>

Download the code Try the code

Take a careful look at the code in the above example. Here we have a check box with an application variable of “checked” bound to it via ng-model. This is variable is initialized to true via “ng-init” in the grid. The code also contains a circular grid of pink color. The circular div has two classes “circle-div and sample-transition. Also, the div contains “ng-show” function which contains value of application variable “checked” (true by default)

Now open the webpage, the checkbox is checked by default and pink circle should be visible on the screen. Now, when user unchecks the checkbox, the value of checked variable becomes false. This means that value of the ng-show animation function also becomes false which actually calls the ng-hide animation function. What ng-hide does is that it looks for the selector that has ng-hide animation added to it. This selector or class is invoked. For instance in our case we have a “sample-transition.ng-hide” selector. When the ng-hide is called, this selector is invoked and it sets the opacity of the div “0” which actually hides the div. Since this is an animation function therefore, the transition: all linear property is also called. We have set the animation time to 1 seconds.

Therefore, when you uncheck the checkbox, the pink circle fades out in 1 seconds time.

AngularJS Include

In the previous article, we studied AngularJS module. In this article we are going to focus on yet another extremely important i.e. AngularJS Include statement. Often times, our project is divided into several webpages. For example, a typical WordPress page consists of three parts: header.php which contains all the header code, a page that contains the main content and a footer.php which contains footer content. So actually to render a complete page, three pages have to be combined together. We can include HTML in AngularJS applications via “ng-inlude” directive. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="">
 	
    
<div ng-include="'heading.html'"></div>
</div>

</body>
</html>

Download the code

Before executing the above code, create a file named “heading.html” and add any html content to it. Place the “heading.html” file in the same folder where your code file is located. Now if you open the code file, you shall see that the div where you added “ng-include” directive contains the html output of the “heading.html” file. This is because “ng-include” directive actually include the contents of the file at the specified location in an AngularJS documents.

Include AngularJS code in Applications

You can also include AngularJs code from one application to the other. This helps create controllers, models and views in different files. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

     <div ng-app = "SelectApp" ng-controller = "SelectController" ng-init="">
         
<div ng-include="'table.html'"></div>
        
      </div>
      
      <script>
         var mainApp = angular.module("SelectApp", []);
         
         mainApp.controller('SelectController', function($scope) {
            $scope.Students = [
                              {name:'John',age:20},
                              {name:'Alice',age:21},
                              {name:'Mark',age:25},
                              {name:'Carry',age:19},
                              {name:'Bron',age:12}
                             ]
             
         });
      </script>  

</body>
</html>

Download the code

Go to the script section of the above code. Here we create a controller which contains a Students array. The array contains five objects. Each object has a name and age variable. Now come to the view section. Here we have a div which contains “ng-include” directive. This directive includes “table.html” file in the application. The contents of “table.html” file are as follows

<table>
<tr ng-repeat="student in Students">
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
</tr>
</table>

Download the code

Now if you run the previous code that contains script and controller, you shall see that name and age of all the objects in the Students array are presented in tabular form, though there is no table in the application. This table is actually generated by “ng-repeat” directive inside the “table.html” file. This is how we add one AngularJS application to another via AngularJS include.

AngularJS Modules

We have covered most of the fundamental AngularJS concepts including views, controllers, models etc. In this article we shall study AngularJS modules. AngularJS modules act as container for controllers and different parts of the application. Modules are basically used to organize application components in a way where they can seamlessly work without depending upon each other. To create AngularJS modules, “angular.module” function is used. Take look at folling

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="NewApp" ng-controller="NewCtrl">

    <input type="text" ng-model="Name">
     <input type="text" ng-model="Age">
{{ Name + " " + Age}}
</div>

<script>

var myapp = angular.module("NewApp", []);

myapp.controller("NewCtrl", function($scope) {
    $scope.Name = "";
    $scope.Age = "";
});

</script>

</body>
</html>

Download the code Try the code

Take a careful look at the script section of the above code. Here we create a module via “angular.module” function. The function takes two parameters, the first parameter is specifies the html element in which AngularJS application shall run. It is “NewApp” in above code. Now the element in which you want to run the AngularJS application must have this “NewApp” as value for the “ng-app” directive. The “angular.module” function returns a handler. In the above code “myapp” variable stores this handler. You can create services, controllers, directives etc in the module via its handler.

In the above code we create a controller named “NewCtrl” which contains two variables Name and Age. Now come back to the view inside the div which has “ng-app” directive. Inside the div we bind these two variables with two text boxes. As soon as the value in text box changes, it is printed on the page.

Adding Directive To Modules

In last example we added controller to the module. Similarly, We can also add directives to AngularJS Modules. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="NewApp" custom-directive></div>

<script> 
var app = angular.module("NewApp", []);

app.directive("customDirective", function() {
    return {
        template : "I am custom directive made by a module."
    };
});
</script>

</body>
</html>

Download the code Try the code

In the above code, we have called “directive” function on modules handler variable. Directive function takes two parameters: the name of the directive and the function. Inside the function, you can add the template of the directive. In the above code, template contains a simple message. Therefore, whenever you add this directive to an html element, the inner html of the message will change to the text in the template.

AngularJS API

API stands for application programming interface. It is a set of built-in functions that are used to perform common tasks. AngularJS API also consists of built-in utility functions that different tasks such as object comparison, case conversion, object iteration etc. In this article we shall some of the most commonly used AngularJS API functions. All the AngularJS API functions are called via “angular” object. Take a look at the following example to see how we can change the case of text via API functions.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="NewApp" ng-controller="NewCtrl">

<p>{{ name1 }}</p>
<p>{{ name2 }}</p>
<p>{{ gender1 }}</p>
<p>{{ gender2 }}</p>
</div>

<script>
var app = angular.module('NewApp', []);
app.controller('NewCtrl', function($scope) {
    $scope.name1 = "mike";
    $scope.name2 = angular.uppercase($scope.name1);
    
    $scope.gender1 = "MALE";
       $scope.gender2 = angular.lowercase($scope.gender1);
});
</script>

</body>
</html>

Download the code Try the code

Take a look at the above code. Go to the script section at the bottom of the page. Here we initialize a controller and create four variables via $scope object. First variable “name1” contains some random name in lowercase. We use angular.uppercase API function to convert the value in the “name1” variable to uppercase. We then store the resultant uppercase value to another variable “name2”. Similary, “gender1” contains value “MALE” in uppercase. We use angular.lowercase API function to convert the value in the “gender1” variable to lowercase. We then store the resultant lowercase value to another variable “gender2”. Finally we print all the four variables on screen to make sure that API functions are performing correctly.

IsNumber & IsString Functions

These functions validate if a value is string or number respectively. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="NewApp" ng-controller="NewCtrl">

<p>{{ message1 }}</p>
<p>{{ message2 }}</p>
<p>{{ number1 }}</p>
<p>{{ number2 }}</p>
</div>

<script>
var app = angular.module('NewApp', []);
app.controller('NewCtrl', function($scope) {
    $scope.message1 = "Welcome to knowledge hills";
    $scope.message2 = angular.isString($scope.message1);
    
    $scope.number1 = 200;
    $scope.number2 = angular.isNumber($scope.number1);
});
</script>

</body>
</html>

Download the code Try the code

Take a look at the above code. Go to the script section at the bottom of the page. Here we initialize a controller and create four variables via $scope object. First variable “message1” contains some random string. We use angular.isString() API function to check whether “message1” contains a valid string or not. We then store the resultant boolean value to another variable “message2”. Similary, “number1” contains some random numeric value. We use angular.isNumber() API function to check whether “number1” contains a valid string or not. We then store the resultant boolean value to another variable “number2”. Finally we print all the four variables on screen to make sure that API functions are performing correctly.

AngularJS Validation

In the previous article we saw how AngularJS can be used to retrieve values entered by the user in form fields. This article extends the previous one. In this article we shall see how AngularJS Validation is performed to validate user input. We know that AngularJS is a JavaScript framework which is a client side language. Therefore, AngularJS validation also occurs on the client side. It is important to note that client side validations are not secure. Therefore you must implement server side validations as well. So let’s start with a very basic example of AngularJS validation.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="">
 	
    <p>Input field is invalid if empty:</p>

    <form name="ValForm">
    <input name="textInput" ng-model="textInput" required>
    </form>

    <p>If the text field input valid?:</p>
    <h1>{{ValForm.textInput.$valid}}</h1>
</div>

</body>
</html>

Download the code Try the code

Take a look at the above code. It contains a text box with a condition “required”. This means that the state of the text box will only be valid if it contains some text. The state of the text box shall be invalid if it is empty. Below the text box, the state is printed via AngularJS expression “ValForm.textInput.$valid”. This expression says that print the validation state of “textInput” field inside the form name “ValForm”. This returns true if the text box has valid input. Otherwise it returns false.

Therefore, if you open the webpage, by default the text box is empty and false will be printed as its condition. Now if you enter something in the text box, false will change to true denoting that text field is in valid state now.

Email Validation

Let’s take a look at another example. Here we shall validate if a text field contains valid email dress. In the text box, we shall use HTML5 email attribute to specify that this text field must contain an email. Then using AngularJS we shall check the state of the text field and notify the user. Have a look at the code.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="">
 	
    <p>Enter a valid email address in text field</p>

    <form name="ValForm">
    <input type="email" name="emailInput" ng-model="emailInput">
    </form>

    <p>If the field contain valid email?</p>
    <h1>{{ValForm.emailInput.$valid}}</h1>
  
    
</div>

</body>
</html>

Download the code Try the code

Now open the above web page in a browser. You should see an empty text box. However, the AngularJS validation expression will still return true. This is because we did not specify that the field is required. Therefore, the expression will return true if the text field is empty. Now, try entering an invalid email. The expression will return false. Now, again enter correct email, the expression will again return true.

AngularJS Forms

Forms are used to get input from the user. A form usually contains html input controls. Some common html input controls are input elements such as text box, password box etc, buttons such as radio buttons, check boxes, drop down list and text area etc. We can use “ng-model” directive to get input values entered by the user via these control. Or in other words AngularJS Forms functions let us retrieve user input from forms. Take a look at the following example, here we shall get what user selected via checkbox.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

    
<div ng-app="" ng-init="val=true">
    <form>
        Check to show a header:
        <input type="checkbox" ng-model="val">
    </form>
    
    <h1 ng-bind="val"></h1>
</div>




</body>
</html>

Download the code Try the code

Open the above page in the browser, you shall see a checkbox which will be checked by default. Below the checkbox, “true” will be printed in heading one. Now if you un-check the check box, the corresponding h1 heading will change to false.

Now take a look at the code. Here we initialize a variable val with true via ng-init directive. We bound this value to check box via “ng-mode” directive. Notice that “ng-model” directive works two ways. It can be used to set the value of the checkbox and to retrieve the value of the checkbox as well. Therefore, since “val” contains true by default and it is bound to checkbox, by default checkbox is checked. Now if checkbox is unchecked the value of “val” variable changes to false. To make sure if value has changed, we print it in the h1 heading.

Capturing input from AngularJS Forms

Now lets create a complete form which contains multiple fields. We shall see how to obtain values from different fields within a form.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

    
<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    First Name:<br>
    <input type="text" ng-model="Student.StudentName"><br>
    Last Name:<br>
    <input type="text" ng-model="Student.StudentAge">
    <br><br>
       Do you require scholarship?:
        <input type="checkbox" ng-model="Student.Scholarship">
    <br></br>
     Gender:
    <select ng-model="Student.Gender">
        <option value="Male">Male
        <option value="Female">Female
    </select>
  </form>
  <p>form = {{Student}}</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.Student = {StudentName: "John", StudentAge: "Doe"};
  
});
</script>


</body>
</html>

Download the code Try the code

Open the above page in the browser. You will see a form with two text fields, one checkbox and one drop down list for gender. Below the form the object has been printed on the screen. In the controller we create “Student” object with two fields: StudentName and StudentAge. These two fields are bound to two text boxes and are by default displayed. The checkbox field is bound to “Student.Scholarship” field. Though this field is not defined in the controller, once you check the checkbox, it is generated at run time and added to the controller. Similarly dropdown field is bound to “Student.Gender” and it is also generated at run time.

The above example shows that binding objects with form is a two way process. You can fill a form field via built-in application variables. Similarly, you can create application variables via form fields.

AngularJS Events

AngularJS contains directives to raise different types of AngularJS events. The event listeners are passed as values to those event directives. Following are some of the most commonly used directives that generate AngularJS events.

  • ng-copy
  • ng-cut
  • ng-blur
  • ng-keypress
  • ng-keydown
  • ng-keyup
  • ng-mouseover
  • ng-mouseenter
  • ng-mouseleave
  • ng-mouseup
  • ng-mousemove
  • ng-paste
  • ng-click
  • ng-dblclick

Handling Mouse Events

Mouse events occur when a person enters mouse on some element, moves it and then leaves the element. Similarly, clicking a mouse on some element also raises an event. Take a look at the following example. Here we shall use “ng-mouseenter” directive to count number of times a mouse enters inside the boundaries of an element.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

<style>
    .box{
        width: 200px;
        height: 200px;
        background-color: skyblue;
    }    
</style>
</head>
<body>

    <div ng-app="EventApp" ng-controller="EventCtrl">

<div class="box" ng-mouseenter="num = num + 1">Enter Mouse here</div>

<h2>{{ num }}</h2>

</div>
<script>
var app = angular.module('EventApp', []);
app.controller('EventCtrl', function($scope) {
    $scope.num = 0;
});
</script>



</body>
</html>

Download the code Try the code

Open the above page in the browser. You should see a square blue box. This is basically a div. Underneath it, there should be number which should be zero when you open the page. Now move the mouse and enter it inside the blue box, the counter will increment to one. Take the mouse out and enter it again inside the blue box, the counter will update to two. Similarly, counter will increment every time you take the mouse inside the blue box. Now take a look at the code, here we have “listened” the mouse enter event on the div using “ng-mouseenter” directive. Inside the controller, we have defined a “num” variable. Every time we enter the mouse inside the boundaries of blue box, increment this num variable by one

Handling Events via Functions

In the last example we incremented the num inside the “ng-mouseenter” directive. In other words we passed variable increment code as a value to the directive. A better way is to encapsulate event handling code inside a function. Then pass this function to the event handler i.e. In the following example we shall handle mouse click event using a function that increments the counter by one. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

<style>
    .box{
        width: 200px;
        height: 200px;
        background-color: skyblue;
    }    
</style>
</head>
<body>

    <div ng-app="EventApp" ng-controller="EventCtrl">

<div class="box" ng-click="increment()">Click Mouse here</div>

<h2>{{ num }}</h2>

</div>
<script>
var app = angular.module('EventApp', []);
app.controller('EventCtrl', function($scope) {
    $scope.num = 0;
    $scope.increment = function() {
    $scope.num++;
    }
});
</script>



</body>
</html>

Download the code Try the code

Take a look at the code, here we have “listened” the mouse click event on the div using “ng-click” directive. Inside the controller, we have defined a “num” variable. Controller also contain a function “increment” which increments the num variable by one. Every time we click mouse inside the boundaries of blue box, increment() function is called and this num variable is increased by one

AngularJS DOM

AngularJS DOM can be used to manipulate HTML elements in different ways. Using AngularJS DOM you can perform functionalities like disabling an enabling an element, showing and hiding and element etc. In this article we shall how to use AngularJS DOM to enable disable HTML elements and show and hide the elements.

Disable and Enable Elements

To disable or enable an element, add “ng-disable” attribute to the opening tag of the element. The value passed to the “ng-disable” directive is the AngularJS application data. The “ng-disable” directive simply binds this value to the disable attribute of the html element. Therefore, if the application data has value “true” for “ng-disable” directive, the corresponding element gets disable and vice versa. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

    <div ng-app="" ng-init="flag=true">

    <p>
    <button ng-disabled="flag">Click to check</button>
    </p>

    <p>
    <input type="text" ng-model="flag">
    </p>



    </div>

</body>
</html>

Download the code Try the code

Open the above web page in the browser. You should see a button and a text box. By default button should be enabled and the text box should contain false. As soon as you enter something other than false in the text box the button will be disabled. Now take a look at the code. It has one AngularJS application variable “flag” which has a default value of false. Next, there is a button element with “ng-disabled” attribute. The value of the attribute is set to “flag”. This means that by default button disable attribute is set to false. Or in other words, button is enabled. However, if you enter something in the text box, the “flag” variable is set to true and button gets disabled.

Hide and Show Elements

You can hide or show html elements via “ng-show” and “ng-hide” directives. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

    <div ng-app="" ng-init="flag=true">


    <p>
    <input type="text" ng-model="flag">
    </p>
        
    <p ng-show="flag">This is paragraph 1</p>

    <p ng-hide="flag"> This is paragraph 2</p>

    </div>

</body>
</html>

Download the code Try the code

In the above application, again flag variable has assigned value true. There are two paragraphs. The first paragraph has “ng-show” directive while the second has “ng-hide” directive. Both have values equal to flag variable. Therefore by default first paragraph will be shown and second will be hidden. If you remove the “true” from text box, second paragraph will become visible and first will hide. This is because flag will have false value now.

AngularJS Select

In the last article, we studied how to create tables via ng-repeat directive. In this article we shall study how to create drop down elements in a web page via AngularJS select. You can use “ng-options” as well as “ng-repeat” directive to create Select element. In this article we shall explain both approaches.

AngularJS Select via “ng-options”

To create drop down list via AngularJS select statement, simply add “ng-options” directive to the opening select tag. The value for the “ng-options” directive is the expression that iterates over items in an array or object. Take a look at the following example to see how to create select drop down list via “ng-options”.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

     <div ng-app = "SelectApp" ng-controller = "SelectController" ng-init="">
         
       <select ng-model="selectedStName" ng-options="student.name for student in Students">
        </select>
        
      </div>
      
      <script>
         var mainApp = angular.module("SelectApp", []);
         
         mainApp.controller('SelectController', function($scope) {
            $scope.Students = [
                              {name:'John',age:20},
                              {name:'Alice',age:21},
                              {name:'Mark',age:25},
                              {name:'Carry',age:19},
                              {name:'Bron',age:12}
                             ]
             
         });
      </script>  

</body>
</html>

Download the code Try the code

Take a careful look at the above code. First go to the script section where we create a “TableController”. This controller contains a “Students” array which contains five objects. Each object has two members name and age. All the variables have been initialized with some values.

Now come back to the top and take a look at the view for the “SelectController”. It contains a Select element. The opening “Select” element contains “ng-options” directive. Inside this directive we iterate upon each object in the Students array and store it in a temporary “student” variable. In each iteration “name” variable of the currently iterating student object is printed inside new “option” element which generated at run time. Since there are five items in the “Students” array, you shall see five items in the drop down list.

AngularJS Select via “ng-repeat”

Like tables, you can also create drop down list via “ng-repeat” directive. To do so, you have to write “ng-repeat” directive inside the opening option element in the Select tag. Take a look at the following example to see how we can bind student names to a drop down list via “ng-repeat”.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

     <div ng-app = "SelectApp" ng-controller = "SelectController" ng-init="">
         
       <select ng-model="selectedStName">
           <option ng-repeat="student in Students">{{student.name}}</option>
        </select>
        
      </div>
      
      <script>
         var mainApp = angular.module("SelectApp", []);
         
         mainApp.controller('SelectController', function($scope) {
            $scope.Students = [
                              {name:'John',age:20},
                              {name:'Alice',age:21},
                              {name:'Mark',age:25},
                              {name:'Carry',age:19},
                              {name:'Bron',age:12}
                             ]
             
         });
      </script>  

</body>
</html>

Download the code Try the code

AngularJS Tables

AngularJS “ng-repeat” directive allows us to create tables in AngularJS. The “ng-repeat” directive repeats the html element to which it is added until all the items in the array are traversed. In AngularJS tables you should add it to “tr” element since this is the element which contains table rows. Take a look at the following example to see how to create AngularJS tables.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

     <div ng-app = "TableApp" ng-controller = "TableController" ng-init="">
         
        <table>
          <tr>
            <th>Name</th>
            <th>Age</th>
          </tr>
          <tr ng-repeat="student in Students | orderBy: 'name'">
            <td>{{ student.name }}</td>
            <td>{{ student.age }}</td>
          </tr>
        </table>
        
      </div>
      
      <script>
         var mainApp = angular.module("TableApp", []);
         
         mainApp.controller('TableController', function($scope) {
            $scope.Students = [
                              {name:'John',age:20},
                              {name:'Alice',age:21},
                              {name:'Mark',age:25},
                              {name:'Carry',age:19},
                              {name:'Bron',age:12}
                             ]
             
         });
      </script>  

</body>
</html>

Download the code Try the code

Take a careful look at the above code. First go to the script section where we create a “TableController”. This controller contains a “Students” array which contains five objects. Each object has two members name and age. All the variables have been initialized with some values.

Now come back to the top and take a look at the view for the “TableController”. It contains a table element. The table element has two rows, one for the header and second for the content. The second “tr” element contains “ng-repeat” directive. Inside this directive we iterate upon each item in the Students array and store it in a temporary “student” variable. With each iteration a new “tr” element is generated at run time with two columns. the first column contains the value for the name variable and the second column contains value for the age variable of the currently iterated object in the Students array. Since there are five items in the “Students” array, you shall see five content rows generated in the table.

Adding Styles To Table

Let us add some styles to our table to make it look more beautiful. Take a look at the following code sample.

<!DOCTYPE html>
<html>
    
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <style>
    table, th , td {
      border: 1px solid grey;
      padding: 7px;
      border-collapse: collapse;
      
    }
    table tr:nth-child(even) {
    background-color: skyblue;
    }
    table tr:nth-child(odd) {
    background-color: #f1f1f1;
    }

   
    </style>
</head>
    
<body>

     <div ng-app = "TableApp" ng-controller = "TableController" ng-init="">
         
        <table>
          <tr>
            <th>Name</th>
            <th>Age</th>
          </tr>
          <tr ng-repeat="student in Students | orderBy: 'name'">
            <td>{{ student.name | uppercase}}</td>
            <td>{{ student.age | uppercase}}</td>
          </tr>
        </table>
        
      </div>
      
      <script>
         var mainApp = angular.module("TableApp", []);
         
         mainApp.controller('TableController', function($scope) {
            $scope.Students = [
                              {name:'John',age:20},
                              {name:'Alice',age:21},
                              {name:'Mark',age:25},
                              {name:'Carry',age:19},
                              {name:'Bron',age:12}
                             ]
             
         });
      </script>  

</body>
</html>

Download the code Try the code

Now if you open the page in browser, you will see alternate table rows styled in different colors. Also you will notice that all the table items are in capital. This is because we have used uppercase filter with each table item inside the “ng-repeat” directive.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .