Getting Started With AngularJS : Part 1

Introduction

In this article, we are about to learn AngularJs. This is just Part 1 of my complete article on AngularJs.

Diving into AngularJs

Now to get started with AngularJs.

The following is all we need:

  • Visual Studio 2012 or 2013 (I am using this IDE for this article).
  • AngularJs script files. “These are necessary 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 preceding pre-requisites in hand we are good to go.

    Now let us follow a new approach for learning when coding instead of learn first and then code. So, if you are with me let's start banging out heads togethe

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

    There ere a few things we need to be familiar with AngularJs.
  • It is an open source framework (now don't get into a debate of whether it is a library or a framework) maintained by the legendary and the dream company of many developers, “Google”.
  • Developers can write a client-side application using AngularJs in the Model-View-Controller (MVC) pattern.
  • AngularJs uses ng-* directives. You will be seeing many now on.

NOTE: If you are continuing then I assume you already have an idea of JavaScript and jQuery (a little will work). I will show few jQuery examples in order to get the differences.

Coffee on… System on full charge… Action!

Basic checking

  1. <html>  
  2.     <head></head>  
  3.     <body>  
  4.         <script src='angularjs.js'></script>  
  5.         <script>  
  6. if(!angular)  
  7. alert("Failed to load angular");  
  8. </script>  
  9.     </body>  
  10. </html>
The preceding program checks 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 the object in your console.

The following  is a very familiar program for us (it lets angular say “Hi” to you):
  1. <html ng-app>  
  2.     <head></head>  
  3.     <body>  
  4.         <input type="text" ng-model="Name" autofocus/>  
  5.         <br/>  
  6. Hey!!   
  7.         <span ng-bind="Name"></span>  
  8.         <br/>  
  9.   
  10. Hey!! {{Name}} again   
  11.         <br/>  
  12.         <br/>  
  13.         <b>*Note: using { {} } does the same as ng-bind</b>  
  14.         <script src='angularjs.js'></script>  
  15.         <script>  
  16. if(!angular)  
  17. alert("Failed to load angular");  
  18. </script>  
  19.     </body>  
  20. </html>"
Heyaaaa… Angular is saying “Hi” to me. Let us now know how Angular is communicating with us.

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

New things observed:
  • “ng-app” in the html tag: this can be compared to a 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 the input tag: I don't need to explain the importance of a model to developers familiar with MVC or MVVM patterns but for the others, this binds the value of HTML controls to our application.
  • “ng-bind” in the span tag: Consider going through the preceding bullet points once againYes, to the output or to show whatever 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 differences, we will understand pretty soon.

Let us compare it to how it works with pure JavaScript.

JavaScript CODE

  1. <html>  
  2.     <body>  
  3.         <p>Implementation of Angular binding</p>  
  4.         <input type="text" onkeyup="myFunction(this)">  
  5.             <br/>  
  6.             <span></span>  
  7.             <script>  
  8. function myFunction(data) {  
  9. var span = document.querySelector('span');  
  10. span.innerText = data.value;  
  11. }  
  12. </script>  
  13.         </body>  
  14.     </html>
We have implemented the functionality of data binding that we saw in Angular using pure JavaScript. By comparing the code we can observe that the brainstorming work of many of humans/developers has been reduced. This way of implicit binding is known as “data-binding” in AngularJs.

Working with Controllers
  1. <html ng-app="IntroApp">  
  2.     <head></head>  
  3.     <body ng-controller="IntroController as movie">  
  4.         <h2>  
  5.             <i>Showing static film details</i>  
  6.         </h2>  
  7.         <br/>  
  8.         <h3>Movie Name : {{movie.MovieName}} </h3>  
  9.         <h3>Hero : {{movie.Hero}} </h3>  
  10.         <h3>Rating on 10 : {{movie.Rating}} </h3>  
  11.         <script src='angularjs.js'></script>  
  12.         <script>  
  13. if(!angular)  
  14. alert("Failed to load angular");  
  15. else{  
  16. var app = angular.module("IntroApp",[]); //defining our module which is considered as namespace or package (only for understanding)  
  17.   
  18. app.controller("IntroController",function(){  
  19. var self = this;  
  20. //lets have some properties  
  21. self.MovieName = "Forest Gump";  
  22. self.Hero = "Tom Hanks";  
  23. self.Rating = 8.3;   
  24. });  
  25. }  
  26. </script>  
  27.     </body>  
  28. </html>

The following  are new things observed:

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


Figure 1 Show Static Film Detail

  • To avoid this we have a class named "ng-cloak" in AngularJs. The following 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 preceding 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 following code.

Adding AJ to the preceding said HTML

  1. <!DOCTYPE html>  
  2. <html  
  3.     xmlns="http://www.w3.org/1999/xhtml">  
  4.     <head>  
  5.         <title></title>  
  6.         <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  7.         <style>  
  8. div.col-sm-2 {  
  9. font-size: 18px;  
  10. }  
  11. label {  
  12. font-weight: normal;  
  13. }  
  14. form {  
  15. background-color: whitesmoke;  
  16. padding: 10px;  
  17. padding-bottom: 10px;  
  18. }  
  19. form > div:not(:first-child) {  
  20. margin-top: 5px;  
  21. }  
  22. div.col-sm-4 > input[type=checkbox]:not(:first-child) {  
  23. margin-left: 10px;  
  24. }  
  25. div.container > div.row {  
  26. margin-top: 10px;  
  27. }  
  28. </style>  
  29.     </head>  
  30.     <body ng-app="RegApp">  
  31.         <div class="container" ng-controller="RegistrationCtrl as reg" ng-init="reg.user.FirstName = 'Aditya'">  
  32.             <form name="registrationForm" ng-submit="reg.SubmitDetails()" class="col-sm-offset-1">  
  33.                 <div class="row">  
  34.                     <div class="col-sm-2">  
  35.                         <label> First Name </label>  
  36.                     </div>  
  37.                     <div class="col-sm-3">  
  38.                         <input type="text" class="form-control" ng-model="reg.user.FirstName" autofocus />  
  39.                     </div>  
  40.                     <div class="col-sm-2 col-sm-offset-2">  
  41.                         <label> Last Name </label>  
  42.                     </div>  
  43.                     <div class="col-sm-3">  
  44.                         <input type="text" class="form-control" ng-model="reg.user.LastName" autofocus />  
  45.                     </div>  
  46.                 </div>  
  47.                 <div class="row">  
  48.                     <div class="col-sm-2">  
  49.                         <label> Gender </label>  
  50.                     </div>  
  51.                     <div class="col-sm-3">  
  52.                         <input type="radio" name="gender" ng-model="reg.user.Gender" value="male" />M  
  53.   
  54.                         <input type="radio" name="gender" ng-model="reg.user.Gender" value="female" />F  
  55.   
  56.                     </div>  
  57.                 </div>  
  58.                 <div class="row">  
  59.                     <div class="col-sm-2">  
  60.                         <label> Address </label>  
  61.                     </div>  
  62.                     <div class="col-sm-3">  
  63.                         <textarea class="form-control" ng-model="reg.user.Address"></textarea>  
  64.                     </div>  
  65.                     <div class="col-sm-2 col-sm-offset-2">  
  66.                         <label> Country </label>  
  67.                     </div>  
  68.                     <div class="col-sm-3">  
  69.                         <select class="form-control" ng-model="reg.user.Country" ng-options="o.name for o in reg.Countries"></select>  
  70.                     </div>  
  71.                 </div>  
  72.                 <div class="row">  
  73.                     <div class="col-sm-2">  
  74.                         <label> Phone </label>  
  75.                     </div>  
  76.                     <div class="col-sm-3">  
  77.                         <input type="tel" class="form-control" ng-model="reg.user.Phone" />  
  78.                     </div>  
  79.                 </div>  
  80.                 <div class="row">  
  81.                     <div class="col-sm-2">  
  82.                         <label> Hobbies </label>  
  83.                     </div>  
  84.                     <div class="col-sm-4">  
  85.                         <input type="checkbox" ng-model="reg.user.Hobbies.Gaming" ng-true-value="1" ng-false-value="0" />Gaming  
  86.   
  87.                         <input type="checkbox" ng-model="reg.user.Hobbies.Travelling" ng-true-value="1" ng-false-value="0" />Travelling  
  88.   
  89.                         <input type="checkbox" ng-model="reg.user.Hobbies.Gardening" ng-true-value="1" ng-false-value="0" />Gardening  
  90.   
  91.                     </div>  
  92.                 </div>  
  93.                 <div class="row">  
  94.                     <div class="col-sm-2">  
  95.                         <button type="submit" disabled class="btn btn-success" style="width:100% !important">Submit</button>  
  96.                     </div>  
  97.                 </div>  
  98.             </form>  
  99.             <div class="row col-sm-offset-1" style="background-color:linen">  
  100.                 <h4>User Information</h4>  
  101.             </div>  
  102.             <div class="row col-sm-offset-1" style="background-color:lightsalmon;">  
  103.                 <div class="row">  
  104.                     <div class="col-sm-1">Name</div>  
  105.                     <div class="col-sm-4">  
  106.                         <span ng-bind="reg.FullName()"></span>  
  107.                     </div>  
  108.                 </div>  
  109.                 <div class="row">  
  110.                     <div class="col-sm-1">Gender</div>  
  111.                     <div class="col-sm-4">  
  112.                         <span ng-bind="reg.user.Gender | uppercase"></span>  
  113.                     </div>  
  114.                 </div>  
  115.                 <div class="row">  
  116.                     <div class="col-sm-1">Address</div>  
  117.                     <div class="col-sm-4">  
  118.                         <span ng-bind="reg.user.Address"></span>  
  119.                     </div>  
  120.                     <div class="col-sm-4">  
  121.                         <span ng-bind="reg.user.Country.name"></span>  
  122.                     </div>  
  123.                 </div>  
  124.                 <div class="row">  
  125.                     <div class="col-sm-1">Phone</div>  
  126.                     <div class="col-sm-4">  
  127.                         <span ng-bind="reg.user.Phone"></span>  
  128.                     </div>  
  129.                 </div>  
  130.                 <div class="row">  
  131.                     <div class="col-sm-1">Hobbies</div>  
  132.                     <div class="row">  
  133.                         <div class="col-sm-1 " ng-repeat="hasHobby in reg.getHobbies()">  
  134.                             <span ng-bind="hasHobby"></span>  
  135.                         </div>  
  136.                     </div>  
  137.                 </div>  
  138.             </div>  
  139.         </div>  
  140.         <script src="/Scripts/jquery-1.9.1.min.js"></script>  
  141.         <script src="/Scripts/bootstrap.min.js"></script>  
  142.         <script src="/Scripts/angular.min.js"></script>  
  143.         <script>  
  144. var app = angular.module("RegApp", []);  
  145. app.controller("RegistrationCtrl", function () {  
  146. var self = this;  
  147. this.Countries = [{ name: 'Country 1', }, { name: 'Country 2', }, { name: 'Country 3', }, { name: 'Country 4', }];  
  148. this.getHobbies = function () {  
  149. var a =[];  
  150. for (var prop in self.user.Hobbies)  
  151. if (self.user.Hobbies[prop] == 1)  
  152. a.push(prop);  
  153. return a;  
  154. }  
  155. this.FullName = function () {  
  156. return self.user.FirstName + " " + (function () { if (!self.user.LastName) return ""; return self.user.LastName; })();  
  157. }  
  158. });  
  159. </script>  
  160.     </body>  
  161. </html>
Woaaaaah!!! It's too long code and confusing! No it isn't, let's first see what we added to the new file. Observe the differences in the following image.


Figure 2 Observe the Diffrence

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

The left part of the image is our basic HTML and the right side is AJ added to HTML. If you can see, there are many changes done to the AJ file, if you can't see then please open the image in a new page and zoom in.

(AJ with HTML is a demonstration using a controller.)

Things observed

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

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 the second file in the browser and start giving values to the fields they get displayed automatically in the user information section.

Do not be confused if you don’t fine the “re.user.*” variables in the controller. This is one of the best things in AJ. When you define a variable inside the scope (in HTML) it will automatically treat 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".


Similar Articles