Angular JS is one of the most powerful JavaScript frameworks. It is used mainly in single page applications.

It enhances existing HTML elements and makes the page more responsive to users.
To add Angular JS to your page, just add the following or similar script tag and you are good to go:

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>

Angular JS terminology

Before we starting working with Angular JS, we need to understand some of these terms:

  1. App
    An HTML page may contain one or more sections of Angular JS directives i.e. not all HTML is part of Angular JS.
    To define, which part of HTML belongs to Angular JS, we specify the ng-app attribute like this:

    <div ng-app="myapp">

    or for the whole body, we write:

    <body ng-app="myapp">
  2. Model
    A model is an object that holds the application data which we can bind with HTML elements.
  3. Controller
    A controller is a JavaScript object that contains attributes and functions. A controller is used to control the flow of data in an Angular JS appliction.
  4. View
    A view is responsible for displaying data to the user.
  5. Module
    Modules are used to separate logic like controllers, applications etc. from each other and hence keeps the code clean.
  6. Service
    Service is a JavaScript object that provides a particular functionality to our Angular JS application. For example, $http service is used to make HTTP requests to server and get data.

Writing our first application

Now, we will see an example that uses Angular JS to say Hello to any name entered in a text box.

Create a new HTML file and add following code to it:

<!doctype html>
<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
   </head>
<body>
   <div>
       This is an Angular JS example <br/><br/>
   </div>

   <!-- this part contains Angular JS code -->
   <div ng-app>
      Name : <input type="text" ng-model="name" placeholder="Enter your name"/>
      <br/><br/>

      Hello <b>{{name}}</b>
   </div>

</body>
</html>

Explanation:

First of all, we added Angular JS from CDN.

Next, we declared a portion of our HTML as Angular JS code by adding the ng-app directive. We did not give any name to the application since we don’t have multiple Angular JS apps on the page for now.

The ng-model attribute creates a variable in Angular JS scope that can be used anywhere in our page using {{ }}

Array Example

In the following example, we will initialize the data and then display the data in an ordered list.

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

      <div ng-app ng-init="countries=['India', 'Japan', 'Russia', 'United States']">

         <ol>
            <li ng-repeat="country in countries">{{country}}</li>
         </ol>

      </div>

    </body>
</html>

The ng-init attribute is used here to create an array named countries. Then with the help of ng-repeat, we run a for-each type loop and print the values of the array.

JSON Array Example

In the following example, we will initialize the data and then display the data in an ordered list.

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

      <div ng-app ng-init="countries=[{name:'India', capital:'New Delhi'}, {name:'Japan', capital:'Tokyo'}, {name:'Russia', capital:'Moscow'}, {name:'United States', capital:'Washington'}]">

         <ol>
            <li ng-repeat="country in countries">{{country.name}} , {{country.capital}}</li>
         </ol>

       </div>

    </body>
</html>

Using Controllers

Controller is a JavaScript object that contains attributes and functions. Each controller accepts $scope parameter that tells the controller which application it is going to control.

Controllers allow us to hide all the application logic in scripts and keep the HTML code clean.

Here is an example that uses controllers to find sum of two numbers entered in a text box.

<!doctype html>
<html>

<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>

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

        myapp.controller('add', function($scope) {
            $scope.first = 0;
            $scope.second = 0;

            $scope.sum = function() {
                 return parseInt($scope.first) + parseInt($scope.second);
            }
        });
    </script>
</head>

<body>

    <div ng-app="myapp" ng-controller="add">

        First number : <input type="text" ng-model="first"/><br/>
        Second number : <input type="text" ng-model="second"/><br/><br/>

        Sum of {{first}} and {{second}} is {{sum()}}

    </div>

</body>
</html>

In this example, we kept our data and logic in a separate script using controller named add.

Then we got the reference of our controller by using the line:

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

The $scope object is the Model here. It contains two data member named first and second as well as a function named sum().

You can separate the scripting logic in different JS files.  For example, above code can also be written as:

<!doctype html>
<html>

<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
    <script type="text/javascript" src="js/controller.js"></script>
</head>

<body>

    <div ng-app="myapp" ng-controller="add">

        First number : <input type="text" ng-model="first"/><br/>
        Second number : <input type="text" ng-model="second"/><br/><br/>

        Sum of {{first}} and {{second}} is {{sum()}}

    </div>

</body>
</html>

and controller.js file will have following code:

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

myapp.controller('add', function($scope) { 
    $scope.first = 0; 
    $scope.second = 0; 
    $scope.sum = function() { 
        return parseInt($scope.first) + parseInt($scope.second); 
    } 
});

Adding filters

Filters are a great way to show only selected data to users. Filters are quick, easy to use and we don’t have to write any code for it, just few directives.

Here is an example that allow us to filter country names by typing in a text box.

<!doctype html>
<html>

<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
</head>

<body>

<div ng-app ng-init = "countries=['Australia', 'France', 'India', 'Indonasia', 'Japan', 'Russia', 'United States']">

    Filter <input type="text" ng-model="name"/>

    <ol>
        <li ng-repeat="country in countries | filter:name">{{country}}</li>
    </ol>

</div>

</body>
</html>

Ajax using $http

In this example, we will get data from the server in JSON format and then display it on our page.

Here is employee-data.php file that returns JSON data:

<?php
    $ar = array();

    $ar[] = array( 'name' => 'Amit', 'gender' => 'Male' );
    $ar[] = array( 'name' => 'Suman', 'gender' => 'Female' );
    $ar[] = array( 'name' => 'Shiva', 'gender' => 'Male' );
    $ar[] = array( 'name' => 'Ruchira', 'gender' => 'Female' );
    $ar[] = array( 'name' => 'Jitender', 'gender' => 'Male' );

    echo json_encode($ar);
?>

Here is ajax.htm file that will print data:

<!doctype html>
<html>

<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>

    <script type="text/javascript" src="js/ajax.js"></script>
</head>

<body>

<div ng-app="emp-app" ng-controller="employeeCtr">

    <ol>
        <li ng-repeat="employee in employees">{{employee.name}}, {{employee.gender}}</li>
    </ol>

</div>

</body>
</html>

And finally ajax.js that will call server URL to get JSON data:

var empApp = angular.module("emp-app", []);

empApp.controller('employeeCtr', function($scope, $http) {

    var url = "employee-data.php";

    $http.get(url).success( function(response) {
        $scope.employees = response;              // get server response and store in employees variable
    });
});