1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Introduction to Angular.JS

Discussion in 'JavaScript and AJAX' started by shabbir, Jun 9, 2015.

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,312
    Likes Received:
    371
    Trophy Points:
    83

    What is AngularJs?



    AngularJS is an open source web application framework; to be more precise, javascript framework. It is introduced mainly to address and overcome the challenges of developing single page applications (SPA). It is framework for front end model-view-controller (MVC) architecture, which simplifies the testing, as well as the development of single page applications.

    How to use AngularJS in your project?



    You can include angularjs library using google cdn in your html file:
    Code:
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    
    Otherwise, you have to download the library in your local storage, save it and use the location of saved library. For example, create a folder named lib where your index.html file is, save the downloaded library inside this folder and name it angular.min.js, then use the location as reference.
    Code:
    <script src="lib/angular.min.js"  type="text/javascript" ></script>
    
    But it is recommended to use Google cdn rather than local storage due to some performance issues.

    AngularJS Directives:



    AngularJS directives are actually HTML attributes with ng prefix. In this section, we will introduce and explore some common built in directives of AngularJS, which are used frequently in angular application. Besides, some other attribute will also be discussed in the following section, which are very important to explain how directive works, such as AngularJS expression, scope etc.

    ng-app

    It defines the root element of angular application. If you don’t use ng-app, It means that you cannot use angular provided functionality in your application.

    ng-model:

    It binds the HTML control field data to application data for further use.

    ng-bind

    It binds the application data, precisely model data to HTML view.

    Let’s explore the above directives (ng-app, ng-model and ng-bind) with a simple example:
    HTML:
    <!DOCTYPE html>
    <html>
    <script src= "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <body>
          <div ng-app="">
            <p>Please fill up the box with your name</p>
            <p> <input type="text" ng-model="Name"></p>
            Hi, <span ng-bind="Name"></span>
        </div>
    </body>
    </html>
    
    Explanation:

    First, we include the angular library in our application.

    In the body section, ng-app directive tells the application that following section will use the angular functionality.

    In the input field, instead of input name, we used ng-model, which will be used later in application to refer our provided data in the input section.

    At last, we want to greet one by the name provided in the model data, so we used ng-bind, and we bind this section with ng-model name.

    AngularJS Expression



    It is not a directive; we can use expression to show values of model variables, as well as independent expression values. Curly braces are used to write expression, in this format: {{expression}}

    Example:

    We will see two examples where expressions are used to output value of independent expressions, and then output the value of model variable(s) with any expression on the variable(s).

    Example 1:

    HTML:
    <!DOCTYPE html>
    <html>
    <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <body>
    <div ng-app="">
    <p> Q. What is the addition result 5 & 10?
    <p>Ans. Result is: {{ 5 + 10 }}</p>
    </div>
    </body>
    </html>
    
    Example 2:
    HTML:
    <!DOCTYPE html>
    <html>
    <script src= "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js "></script>
    <body>
    
    <div ng-app="">
    What is your name?
    <p> Name: <input type="text" ng-model="name"></p>
    
    <br>
    Hi, {{name}}, how are you?
    </div>
    
    </body>
    </html>
    
    Explanation:

    In first example, the expression is used to add two predefined numbers and show their addition result. We did the addition inside AngularJs expression and then the addition result is shown.

    In the second example, the expression is used to output the model variable value, we can also do some operation on the model variable and then output it on the screen using expression.
    ng-controller

    It works with application logic. A controller performs a specific task, sometimes multiple tasks and makes the result available to view.

    ng-module

    This directive contains different parts of the application which includes controller, service, factories, filter etc.

    $scope

    It is a bridge between controller and view in AngularJS. It is created by angular. Controller works with application logic, performs some operation on available data and generates some result. The result is then made available to view with $scope variable. When you define a controller, you have to inject $scope in it.

    Let’s incorporate ng-controller, ng-module and $scope in an example to get better understanding.

    Example:
    HTML:
    <!DOCTYPE html>
    <html>
    <script src= "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <body>
    
    <div ng-app="testApp" ng-controller="InfoCtrl">
    
    City: <input type="text" ng-model="city"><br>
    Country: <input type="text" ng-model="country"><br>
    <br>
    You live in: {{address()}}
    
    </div>
    
    <script>
    var info = angular.module('testApp', []);
    info.controller('InfoCtrl', function($scope) {
        $scope.city = "";
        $scope.country = "";
        $scope.address = function() {
            return $scope.city + "," + $scope.country;
        }
    });
    </script>
    </body>
    </html>
    
    Explanation:

    At first, we gave a name of our application and controller.

    ng-app="testApp" ng-controller="InfoCtrl"

    Then we used two model variable city and country to take input from user.

    Then we used a function call named address in the expression, the expression evaluates the value of address function and outputs it. But from where did we define the address function? It is in the controller.

    Then we defined a module named info. To define a module, the format is:

    var moduleName = angular.module(applicationName, [dependency])

    Let us leave the dependency section for now, we will discuss it when it comes to focus.

    Then we defined our controller InfoCtrl, inject $scope in it. The format is:

    moduleName.controller(controllerName, function($scope)){
    }

    Inside the controller, we defined $scope.city and $scope.country variable. These two variables are bind with the model.

    Then we defined $scope.address function. This address function is accessible from the view, outside from the controller because of $scope. If we used address instead of $scope.address in the controller, then it would be inaccessible from outside the controller definition. This function returns a concatenated string of city and country variable, separated by a comma (,).
    At last, from the view, we can call the address function, remember that in the view, you don’t need to use $scope. It is used in the controller.

    ng-if

    This directive performs basic if operation of computer programming. It checks the condition, executes the following blocks if condition is true, and otherwise neglects it.
    HTML:
    <!DOCTYPE html>
    <html>
    <script src= "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <body>
    
    <div ng-app="testApp" ng-controller="InfoCtrl">
    
    Q. Do you have any child?
    <div ng-if ="hasChild() == true">
     Ans. Yes, I have.
    </div>
    <div ng-if ="hasChild() == false">
     Ans. No, I don't.
    </div> 
    
    </div>
    
    <script>
    var info = angular.module('testApp', []);
    info.controller('InfoCtrl', function($scope) {
           $scope.hasChild= function() {
            return false;
        }
    });
    </script>
    </body>
    </html>
    
    Explanation:

    In controller, we have defined a function named hasChild, which returns true or false.

    In view, hasChild function is called inside ng-if directive, checks whether the return value is true or false, and displays the answer accordingly.

    ng-switch

    This directive works as switch case of other programming language. Among a set of choice, it selects one and executes next block accordingly.
    HTML:
    <!DOCTYPE html>
    <html>
    <script src= "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <body ng-app>
      Type a number between 1 to 3: <br>
    <input type="text" ng-model="number"/>
      <div ng-switch="number">
        <div ng-switch-when="1">1</div>
        <div ng-switch-when="2">2</div>
        <div ng-switch-when="3">3</div>
        <div ng-switch-when="">Empty</div>
        <div ng-switch-default>Not in range</div>
      </div>
    </body>
    </html>
    
    Explanation:

    The input field is a model; we want to show the number that is entered into it, in the next line. The range is 1 to 3.

    We used the model number in ng-switch directive to check its value, and then display the number accordingly. It has a default case too.

    ng-init

    This directive initializes application variables.
    HTML:
    <html>
    <script src= "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <body>
    <div ng-app="" ng-init="check=false">
    <p>
    <input type="checkbox" ng-model="check"/>Hide Button
    </p>
    {{check}}
    </div> 
    </body>
    </html>
    
    Explanation:

    In above example, there is a checkbox named check, which is used as model.

    The value of this model variable is initialized at the start of the angular application using ng-init directive.

    ng-show

    Depending on the value of the provided Boolean expression, this directive shows any element.
    HTML:
    <!DOCTYPE html>
    <html>
    <script src= "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <body>
    <div ng-app="" ng-init="check=false">
    <p>
    <input type="checkbox" ng-model="check "/>Show Button
    </p>
    <p>
    <button ng-show="check">Button</button>
    </p>
    </div> 
    </body>
    </html>
    
    Explanation:

    There is a checkbox as an input type, depending on its value, we will show a button. If checkbox is checked, then the button will be showed, and if it is unchecked, the following button will be disappeared.

    The state of checkbox is modeled in a variable named check. Initially, its state is made false using ng-init directive, ng-show directive checks the state of the model variable check to display the button. If checkbox state is true, value of check is also true and button is shown.
    Initially, when the page is loaded, checkbox is unchecked, so no button is shown. When we check the checkbox, the value becomes true and the button is shown accordingly.

    ng-hide

    It works like ng-show directive, in reverse logic. It evaluates a Boolean expression, and hides any element if the expression returns true and shows otherwise.
    HTML:
    <!DOCTYPE html>
    <html>
    <script src= "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <body>
    <div ng-app="" ng-init="check=false">
    <p>
    <input type="checkbox" ng-model="check"/>Hide Button
    </p>
    <p>
    <button ng-hide="check">Button</button>
    </p>
    </div> 
    </body>
    </html>
    
    ng-repeat

    This directive works like loop of programming language. It takes an item from a collection of item each time and performs any desired operation on that item.
    HTML:
    <!DOCTYPE html>
    <html>
    <script src= "//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <body>
    <div ng-app="testApp" ng-controller="TestCtrl">
      <ul>
        <li data-ng-repeat="os in operatingSystems">
          {{ os}}
        </li>
      </ul>
    </div>
    
    <script>
    var app = angular.module('testApp', []);
    app.controller('TestCtrl', function($scope) {
          $scope.operatingSystems= ['Windows','Linux','Mac OSX'];
    });
    </script>
    </body>
    </html>
    
    Explanation:

    In controller named TestCtrl, we declared an array named operatingSystem. It is accessible from view as it is defined with $scope.

    Our objective is to show every element from the array.

    From view, using ng-repeat directive, we took out one element each time from the array, named it as os, and displayed its value using expression {{os}}.

    Here we have introduced AngularJS and discussed some basic directives of it. These directives are used frequently in almost every Angular application. Go through the sample code provided with every directive and try to understand what is going on. Hopefully, it will help you to understand the working procedure of AngularJS.
     

Share This Page