Thursday, 14 January 2016

Angularjs Tutorial for beginners – Part1

This articles is for whom who is going to start working on angularJs and want an over view of it and basic directive. Target audience is only AngularJs beginners.


Once you reed you will get the answer of.
1.       What is angularJs
2.       What is directive in angularJs
3.       How data is binding in angularJS.
4.       What is expression in angularJs
5.       What is modules and controller in Angularjs
6.       How angularjs follow MVC architecture
7.       What is two way binding in angular.

What is AngularJs


       AngularJS is a structural framework for dynamic web apps.



       It extend HTML's syntax to express your application's components clearly with Directives, and binds data to HTML with Expressions.

       AngularJS is a JavaScript framework. It is a library written in JavaScript. Neet to include library as;

                <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
Download AngularJs Library from : https://code.angularjs.org/1.3.5/

       Open-source web application framework mainly maintained by Google

1.    Angular Directive

It extend the HTML syntax with extension, It attaches with the DOM when browser run the application. Each directive of angular start with ng-.

There are many inbuilt directive provided by angular and it allow you to create your own custom directive also.

Basic Directive we will look in this article as:
       ng-app directive defines an AngularJS application.
       ng-model directive binds the value of HTML controls (input, select, textarea)
       ng-bind directive binds application data to the HTML view
       ng-init directive  for initialize the model Value.
       ng-repeat directive for looping of Model collection
Lets see the first lab 1 for example of above directive.


Lab 1:


Sample 1: Simple Data Binding with Model

This is simple binding of model with data;
If you will see the below code for any angular code we have to give ng-app, it says browser that please treat my code as angular code and bind it like the angular.
AngularJs is work under the MVC concept in below description you can see how we have model and View(binding)  of the model we are using. Later will tell how we use controller in angular.
For initial value need to give ng-init


ng-model -  it work as the model for angular, where you defined your property.

ng-Bind  or {{}} – here you will bind your model to view.

I used one more directive which is not required at this stage but for explanation I have given.

ng-model-options : as it is two way binding when you are given any value in the textbox automatically it reflect but if you want to get it after onblur or any other than need to use this directive.
Code Snippet
@{
    ViewBag.Title = "Sample1";
}

<h2>Sample 1 :Simple Data Binding with Model</h2>

<div ng-app="" ng-init="name1='Ravi'">
    <br /><b> Regular</b><br />
    <br />
    <p>Name: &nbsp; <input type="text" ng-model="name1"></p>
    <br />
    <b> Given Name : </b> <p ng-bind="name1"></p>
    <br /><br />
    <b> Given Name : </b>{{name}}

    <br /><br /><b> Model Option for update [ Update while onblur]</b><br /><br />
    <p>Address: &nbsp; <input type="text" ng-model="address" ng-model-options="{ updateOn: 'blur' }"></p>
    <br />
    <b> Given Address : </b> <p ng-bind="address"></p>
    <br /><br />
</div>

You will get the Screen like below; You can download the full code from github. Check with the link above.
Screen (output):



Lab 2

Sample3 - : Simple Data Binding with Directive Repeat

Binding the angular array of data with ng-repeat.
If you will see the code snippet there we are using the ng-app same like previous and ng-init where we are initializing the array of values and ng-repeat, where we are repeating the array values and another array to binding the object of array. That you can use to show list of records in table like grid.

[ We will see it in another lab]
Code snippet
@{
    ViewBag.Title = "Sample3";
}

<h2>Sample3 - :Simple Data Binding with Directive Repeat </h2>

<br />
Binding the arry of records <br />

<b> <u>Single Array</u></b> <br />
<div ng-app="" >
    <div ng-init="alphabet=['Apple','Ball','Cat']">
        <ul>
            <li ng-repeat="x in alphabet">
                {{ x }}
            </li>
        </ul>



    </div>

    <br /><br />
    <b> <u>Multi Array</u></b> <br />

    <div ng-init="alphabets=[
{text:'A',stands:'Apple'},
{text:'B',stands:'Ball'},
{text:'C',stands:'Cat'}]">

        <ul>
            <li ng-repeat="x in alphabets">
                {{ x.text }}  -  {{ x.stands }}
            </li>
        </ul>

    </div>
  
</div>
Screen (output):

2.    Angular Expression

Performing operation between two curly braces {{}}.
As in below example you can see that 2+3 it will treat as the expression and perform the operation.
Double braces: {{ expression }}. e.g. {{ 2 +3 }}
Lab 3

Code snippet
As in below code snippet you will see how we will use expression {{}}. And by this it will perform the operations.


<div ng-app="" ng-init="Prop.FirstNumber=0;Prop.SecondNumber=0">
    <br /><br />
    <b> <u>Simple Expression</u></b> <br />
    Result of { {2 * 2 + 2 /2}}    as <br />


    {{2 * 2 + 2 /2}}  @* hard codede value *@
    <br /><br />
    <b><u>Model Based Expression</u></b>
    <br /><br />
    <p>First Number : &nbsp; <input type="text" ng-model="Prop.FirstNumber"></p>
    <br /><br />
    <p>Second Number : <input type="text" ng-model="Prop.SecondNumber"></p>
    <br /><br />
    <b> Add : </b>{{ (Prop.FirstNumber* 1) + (Prop.SecondNumber * 1)}}  @*Dynamic expression -- >*@
    <br /><br />
    <b> Mul : </b>{{Prop.FirstNumber * Prop.SecondNumber}}
</div>


Screen (output):

When ever you give the value in first it will calculate on text enter and display result

Some More directive that you can use and we will see the examples also.
More Directives >>>
ng-class
Lets class attributes be dynamically loaded.
ng-controller
Specifies a JavaScript controller class that evaluates HTML expressions.
ng-show & ng-hide
Conditionally show or hide an element, depending on the value of a boolean expression.
Show and hide is achieved by setting the CSS display style.
ng-switch
Conditionally instantiate one template from a set of choices, depending on the value of a selection expression.
ng-view
The base directive responsible for handling routes that resolve JSON before rendering templates driven by specified controllers.
ng-if
Basic if statement directive that allow to show the following element if the conditions are true.
When the condition is false, the element is removed from the DOM. When true, a clone of the compiled element is re-inserted
ng-aria
A module for accessibility support of common ARIA attributes.
ng-animate
A module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives.

3.    AngularJS Controllers

As I discussed that angularJs work on MVC model so there I am demonstrating how the Controller come into picture of angularJS.

       Contain only the business logic needed for a single view

       Controller is defined by a JavaScript constructor function that is used to augment the Angular Scope.

       Controller is attached to the DOM via the ng-controller directive.

       Use controllers to:
§  Set up the initial state of the $scope object.
§  Add behavior to the $scope object


What is Scope ??

       Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application.

You can see different between $scope and $rootScope from below link.




Lab 4

Code snippet

Now you can see the below code snippet as we defined javascript code over there and given the name to the module which
1.       we are working as myApp. angular.module('myApp' Mostly in application there will be one module. ng-app="myApp". For each view you can place a multiple controller or single controller there we have place single controller which bind with module.

2.  Name of controller given as control app.controller('control', function ($scope)

3.  Need to defined in HTML tag and scope of that controller will be between start to end;  There we have use $scope which defined the scope for your model that you defined.


4.       In previous example we defind model in html now we defined it in Script as generally we required and bind it to HTMl view.

Start >>>>>>> <div ng-app="myApp" ng-controller="control">
    <br /><br />
    First Name: <input type="text" ng-model="firstName"><br>
    Last Name: <input type="text" ng-model="lastName"><br>
    <br><br />
    <b>Controller Modle result </b><br />
    Full Name: {{firstName + " " + lastName}}

    <br> <br />
    <b>Result by Function call</b><br />

Full Name: {{Result()}} @* Instead of model returning as a function *@

End >>>> </div>

<script>
    var app = angular.module('myApp', []);
    app.controller('control', function ($scope) {
        $scope.firstName = "Satya";
        $scope.lastName = "Rathore";

        $scope.Result = function()
        {
            return $scope.firstName + " " + $scope.lastName;
        }
    });
</script>
Screen (output):


Looking like its a big article so split it into another parts.

In Next we will see.
·         AngularJS Filters
·         AngularJS Events             
·         AngularJS Forms
·         AngularJS  Input Validation
·         AngularJS $http and SQL Integration

Part 2 >>
http://www.getmscode.com/2016/01/angularjs-tutorial-for-beginners-part2.html


Practice application Login Form in AngularJS
http://www.getmscode.com/2015/11/angularjs-with-mvc-login-form-tutorial.html
Sample crud operation
http://www.getmscode.com/2016/03/simple-crud-operation-using-angularjs.html

1 comment:

  1. Thanks for sharing this webpage.It is really helpful.Keep sharing more with efficient new like this.
    Regards,
    Angularjs course in Chennai | Angularjs Training in Chennai

    ReplyDelete

Others

You will like to read it