Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Diving into AngularJS Part-1

4.25/5 (6 votes)
24 May 2015CPOL6 min read 14.9K   86  
This article will help you to understand Angular JS right form basics

Introduction

In this article, we are about to learn AngularJS. This is just a Part-1 of my complete article on Angular JS.

Diving into Angular JS

Getting started with Angular JS.

All we need are:

  • Visual Studio 2012 or 2013 (I am using this IDE for this article)
  • Angular JS script files. “These are mandatory for us to work ;)” You can get them from https://angularjs.org/
  • SQL Server 2012 or 2014 (I am using 2012 for database work, you know any app or site is of no use if we really don’t have data in it. So, get a DB to work with data)

Okay…!!! If you have all the above said pre-requisites in hand we are good to go.

Now let us follow a new approach of learning while coding instead of learn first and then to code. So, if you are with me let’s start banging out heads together…

BTW, the application we are about to develop is on Movies Database as I am a movies lover “I watch them a lot”

Few things we have to know about Angular JS

  • It is an open source framework (now don’t get into debate whether it is library or framework) maintained by the legendary and one of the dream company of many developers “Google”.
  • Developers can write client side application using AngularJS in MVC(Model-View-Controller) pattern.
  • AngularJS uses ng-* directives. You will be seeing a lot now on.

*NOTE: If you are going forward I assume that you already have idea on JavaScript and JQuery (a lil will work). I will show few JQuery examples inorder to get the differences.

Coffee on… System on full charge… Action :D

I. Basic checking

HTML
<html>
    <head>
    </head>
    <body>
        <script src='angularjs.js'></script>
        <script>
            if(!angular)
                alert("Failed to load angular");
        </script>
    </body>
</html>

The above program is to check if we have located our AngularJS file correctly or not. What to check what angular has?? Then add this line to your script tag “console.log(angular);”, you can find object in you console. 

II. Most familiar program for us (“Let angular say “Hi” to you)

HTML
<html ng-app>
    <head>
    </head>
    <body>
    
        <input type="text" ng-model="Name" autofocus/> <br/>
        Hey!! <span ng-bind="Name"></span> <br/>
        
        Hey!! {{Name}} again <br/><br/>
        
        <b>*Note: using { {} } does the same as ng-bind</b>
    
        <script src='angularjs.js'></script>
        <script>
            if(!angular)
                alert("Failed to load angular");
        </script>
    </body>
</html>

Heyaaaa… Angular saying “Hi”to me… :D let us now know how angular is communicating with us.

Observe the code, we have added few terms when compared to our first program.

New things observed:

  • “ng-app” in html tag: this can be compared with namespace for .Net developers or package for Java people. It’s obvious that we always have our controller under them (namespace/package).
  • “ng-model” in input tag: I don’t have to mention the importance of a model to developers familiar with MVC or MVVM patterns but for others this binds value of html controls to our application.
  • “ng-bind” in span tag: Consider going through above bullet point once again… Yes, to output or to show whatever the value we have in our model we use this directive.
  • {{}} :  now, what is this?!!! This works the same as ng-bind does. Forget about the difference, we will understand pretty soon.

Let us compare the same way of work around with pure Javascript

JS CODE

HTML
<html>
 <body>

   <p>Implementation of Angular binding</p>

   <input type="text" onkeyup="myFunction(this)"><br/>
   <span></span>

   <script>
      function myFunction(data) {
        var span = document.querySelector('span');
        span.innerText = data.value;
      }
   </script>

 </body>
</html>

We have implemented the functionality of data binding which we have seen in angular using pure Javascript. By comparing the code we can observe that a lot of human/developer brainstorming work have been reduced. This way of implicit binding is known as “data-binding” in angularJS.

Working with Controllers:

HTML
<html ng-app="IntroApp">
    <head>
    </head>
    <body ng-controller="IntroController as movie">
    
        <h2><i>Showing static film details</i></h2> 
        <br/>
        
        <h3>Movie Name : {{movie.MovieName}} </h3>
        <h3>Hero : {{movie.Hero}} </h3>
        <h3>Rating on 10 : {{movie.Rating}} </h3>
        
        <script src='angularjs.js'></script>
        <script>
            if(!angular)
                alert("Failed to load angular");
                else{
                    var app = angular.module("IntroApp",[]); //defining our module which is considered as namespace or package (only for understanding)
                    
                    app.controller("IntroController",function(){
                        var self = this;
                        //lets have some properties
                        self.MovieName = "Forest Gump";
                        self.Hero = "Tom Hanks";
                        self.Rating = 8.3;                        
                    });
                    
                }
        </script>
    </body>
</html>

New things observed:

  • angular.module(“IntroApp",[]) : we have already seen that “angular” is object, if you have missed that section do “console.log(angular)” in script and you can see an object in console log.   
    • Module is a method of angular which takes appName as first argument and notice the array in second argument.  If we have any dependencies we will pass them in the array (second parameter).
    • We will see about these dependencies later, for now, make not of few dependencies like $ngRoute,$scope,$rootScope,$routeParams etc.,
    • For our understanding I have stored angular.module(…) to a variable named app. We can also go for chain method calling as
      • angular.module(“IntroApp”,[]).controller(“……..
  • angular.controller("IntroController",function(){ }) : Our wait for controller has come finally. Controller plays a major role in filtering data which it receives from WebAPI or some service you are consuming.
    • Controller is a method of angular which takes controllerName as first argument and its anonymous function as second parameter.
    • The function contains functions and properties required as shown in above example.
  • Now, try refreshing you page continuously… have you observed that the curly brace things are being display for a fraction of second?!!! Yes, they are as shown in the below figure. And this is the difference between this curly brace thing and “ng-bind” directive. “Oh c’mon its just a fraction of second”, you might be in this way of thinking but think if we are consuming a service and we have to wait for  2-5 seconds for its response. Isn’t it will be awkward for us to show those curly braces to our customer?!!! 

Double Braces image

  • To avoid this we have class named "ng-cloak" in angularJS. Below is the syntax
    • [ng\:cloak], [ng-cloak], .ng-cloak {
        display: none !important;
      }
    • Add ng-cloak as you add autofocus to an element as shown below
      • <h3 ng-cloak >Movie Name : {{movie.MovieName}} </h3>
  • Make the above said changes to our ControllerIntro.html file and try refreshing now. You will not see the curly braces until the data is loaded.

In the attached ZIP file you can find a (RegistrationsAJ - HTML) HTML page. Download it for reference with the below code

Adding AJ to the above said HTML:

HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title></title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />

    <style>
        div.col-sm-2 {
            font-size: 18px;
        }

        label {
            font-weight: normal;
        }

        form {
            background-color: whitesmoke;
            padding: 10px;
            padding-bottom: 10px;
        }

            form > div:not(:first-child) {
                margin-top: 5px;
            }
        div.col-sm-4 > input[type=checkbox]:not(:first-child) {
            margin-left: 10px;
        }

        div.container > div.row {
            margin-top: 10px;
        }
    </style>

</head>

<body ng-app="RegApp">

    <div class="container" ng-controller="RegistrationCtrl as reg" ng-init="reg.user.FirstName = 'Aditya'">
        <form name="registrationForm" ng-submit="reg.SubmitDetails()" class="col-sm-offset-1">
            <div class="row">
                <div class="col-sm-2"> <label> First Name </label></div>
                <div class="col-sm-3">
                    <input type="text" class="form-control" ng-model="reg.user.FirstName" autofocus />
                </div>

                <div class="col-sm-2 col-sm-offset-2"><label> Last Name </label> </div>

                <div class="col-sm-3">
                    <input type="text" class="form-control" ng-model="reg.user.LastName" autofocus />
                </div>
            </div>

            <div class="row">
                <div class="col-sm-2"><label> Gender </label></div>
                <div class="col-sm-3">
                    <input type="radio" name="gender" ng-model="reg.user.Gender" value="male" />M
                    <input type="radio" name="gender" ng-model="reg.user.Gender" value="female" />F
                </div>

            </div>
            <div class="row">
                <div class="col-sm-2"><label> Address </label></div>
                <div class="col-sm-3">
                    <textarea class="form-control" ng-model="reg.user.Address"></textarea>
                </div>

                <div class="col-sm-2 col-sm-offset-2"><label> Country </label> </div>
                <div class="col-sm-3">
                    <select class="form-control" ng-model="reg.user.Country" ng-options="o.name for o in reg.Countries"></select>
                </div>
            </div>

            <div class="row">
                <div class="col-sm-2"><label> Phone </label></div>
                <div class="col-sm-3">
                    <input type="tel" class="form-control" ng-model="reg.user.Phone" />
                </div>
            </div>

            <div class="row">
                <div class="col-sm-2"><label> Hobbies </label></div>
                <div class="col-sm-4">
                    <input type="checkbox" ng-model="reg.user.Hobbies.Gaming" ng-true-value="1" ng-false-value="0" />Gaming
                    <input type="checkbox" ng-model="reg.user.Hobbies.Travelling" ng-true-value="1" ng-false-value="0" />Travelling
                    <input type="checkbox" ng-model="reg.user.Hobbies.Gardening" ng-true-value="1" ng-false-value="0" />Gardening
                </div>
            </div>

            <div class="row">
                <div class="col-sm-2">
                    <button type="submit" disabled class="btn btn-success" style="width:100% !important">Submit</button>
                </div>
            </div>
        </form>

        <div class="row col-sm-offset-1" style="background-color:linen">
            <h4>User Information</h4>
        </div>

        <div class="row col-sm-offset-1" style="background-color:lightsalmon;">
            <div class="row">
                <div class="col-sm-1">Name</div>
                <div class="col-sm-4"> <span ng-bind="reg.FullName()"></span> </div>
            </div>

            <div class="row">
                <div class="col-sm-1">Gender</div>
                <div class="col-sm-4"> <span ng-bind="reg.user.Gender | uppercase"></span> </div>
            </div>

            <div class="row">
                <div class="col-sm-1">Address</div>
                <div class="col-sm-4"> <span ng-bind="reg.user.Address"></span> </div>
                <div class="col-sm-4"> <span ng-bind="reg.user.Country.name"></span> </div>
            </div>

            <div class="row">
                <div class="col-sm-1">Phone</div>
                <div class="col-sm-4"> <span ng-bind="reg.user.Phone"></span> </div>
            </div>

            <div class="row">
                <div class="col-sm-1">Hobbies</div>
                <div class="row">
                    <div class="col-sm-1 " ng-repeat="hasHobby in reg.getHobbies()">
                        <span ng-bind="hasHobby"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <script src="/Scripts/jquery-1.9.1.min.js"></script>
    <script src="/Scripts/bootstrap.min.js"></script>
    <script src="/Scripts/angular.min.js"></script>
    <script>
        var app = angular.module("RegApp", []);
        app.controller("RegistrationCtrl", function () {
            var self = this;
            this.Countries = [{ name: 'Country 1', }, { name: 'Country 2', }, { name: 'Country 3', }, { name: 'Country 4', }];
            this.getHobbies = function () {
                var a =[];
                for (var prop in self.user.Hobbies)
                    if (self.user.Hobbies[prop] == 1)
                        a.push(prop);
                return a;
            }

            this.FullName = function () {
                return self.user.FirstName + " " + (function () { if (!self.user.LastName) return ""; return self.user.LastName; })();
            }
        });
    </script>
</body>
</html>

 

Woaaaaah!!! Its too long code and confusing… isn’t so, lets first find out what we added to the new file. Observe the differences in the below pic

  Missing

If the above image is missing => https://onedrive.live.com/redir?resid=76572BF81D528DBA!7162&authkey=!AEVQ0saUghWYbao&v=3&ithint=photo%2cPNG

Left part of the image is our basic HTML and the right side is AJ added to HTML. If you can see there are lots of changes done to the AJ file, if you can’t see please open image in new page and zoom in.

(AJ with HTML is a demonstration using controller)

 

Things observed:

ng-init: This directive is used to initiate values before loading. So, when you open this file you can see the field FirstName is populated with Name already.

                Try removing ng-init and see your console and you will find an error. It is only because we haven’t created a variable reg.user inside our controller. This variable will be initiated or added to the controller’s scope only when we start giving values to our HTML fields.

 

When you open second file in browser and start giving values to the fields they get displayed automatically in the user information section.

Do not get confused if you don’t fine the “re.user.*” variables in controller. This is one of the best this in AJ. When you define a variable inside the scope (in HTML) it will automatically treats that variable as its member.

 

And the next thing we have is Form Validations:

                We will see form validations and Services in AJ in "Diving into AJ part 2"

Points of Interest

Play around with code to have more headache ;) the more you play with code the easy it becomes to code

History

Keep a running update of any changes or improvements you've made here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)