Saturday, March 15, 2014

Basics of Angularjs

This article introduces the basics of Angularjs. I collected the following information from various web resources and have attempted to explain them in an easy way.
  • Angularjs is a JavaScript MVC framework created by Google to build properly architectured and maintainable web applications
  • It decreases emphasis on directly handling DOM manipulation from the application logic
  • It employs efficient two-way data binding and sensible MVC implementation
  • We can create our own HTML custom tags and attributes
  • We need to download the Angularjs from the following link.

    Angularjs
     
  • Angularjs revolves around Model, View and Controller
  • Using Angularjs we can eliminate the use of document.getelemetbyid('..') and so on.
Before proceeding I am assuming we are familair with the MVC framework.

To understand MVC we can go to the following:
ASP.NET MVC Overview

We will learn the following things in AngularJs:
  1. Directives
  2. Expressions
  3. $scope object
  4. Controllers
  5. Model
  6. Module
  7. Filters
  8. Data binding
The following is an explanation of the things listed above.

1. Directives

Directives can be used to create custom HTML tags that serve new, custom widgets. They can also be used to "decorate" elements with behavior and manipulate DOM attributes in interesting ways. HTML consists of static pages but we can now use extended HTML that provides dynamic features by adding attributes, element and comments. 

We generally have directives starting with "ng-".
 
We need to add a directive to an existing HTML form using "np-app" as in the following:

<html  ng-app>

We have the following directives:
  • ng-app

    This will activate the AngularJS to the entire document

    We need to add to a HTML form like this: <html  ng-app>
     
  • ng-model
     
    This links the model and the form. This means that any changes to the control update the data in our model and when we update the model it updates the control. We can define the model as in the following:

    <input ng-model="modeltest">
     
  • ng-controllers

    In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope as in the following:

    <div ng-controller="modeltest">

    Here we need to define the controller with the name "modeltest" in a separate JavaScript file. Other directives are the following: 
     
  • ng-click
  • ng-repeat
  • ng-view
  • ng-bind

    We have various ways to define a directive and all of the following have the same meaning:
     
  • <input ng-model="modeltest">
  • <input data-ng:model=" modeltest ">
  • <input ng:model=" modeltest ">
  • <input ng_model=" modeltest ">
2. Expressions
  • The {{   }} are a declarative way of specifying a data binding location in HTML. AngularJS will automatically update this text.
  • Using an expression we can do data binding, as in {{ }}.
Expression example
AngularJs Expression
Output of the above HTML

The following output will be will be rendered in the DOM:

1+2=3

3. Let's start with a sample example.
HTML file
<html ng-app>
<head>
    <script src="script/angular.min.js"></script>
</head>
<body>
    <div>
        <input type="text" ng-model="uservalue" placeholder="enter text here">
        <h1>
            Hello, {{ uservalue }}</h1>
    </div>
</body>
</html>
 
From the code above we can try to understand the following terms:
  1. ng-model: is a model directive that can be bi-directional. Here the model name is the uservalue
  2. {{ uservalue }} : {{ }}  are expressions in Angularjs and the uservalue inside the {{ }} is to be displayed on the HTML form.
  3. The following is the output of the HTML code above.
HTML outputHTML output
  4. Angular Module
An Angular module is simply a collection of functions defined in a JavaScript file. 

How to define a module in angularjs:
  1. First create sample.js
  2. Inside the sample.js file we need to add the following line:

     var app = angular.module('myApp', []);

    This line creates the Angular module named "myApp". 
     
  3. We need to define this module in our DOM, the module name is "myApp"
  4. <html ng-app="myApp">
5. Controllers
In Angular, a Controller is a JavaScript constructor function that augments the Angular Scope.

We have code below in the table, the left column contains HTML code and the right column contains Sample.js. Here we are defining MyUserController in Sample.js. We can define a controller in HTML form using the "ng-controller" directive.

HTML file
<html ng-app>
<head>
    <script src="angular.min.js"></script>
    <script src="sample.js"></script>
</head>
<body>
    <div ng-controller="MyUserController">
        Your name:
        <input type="text" ng-model="name">
        <button ng-click='sayHello()'>
            greet</button>
        <hr>
        {{greeting}}
    </div>
</body>
</html>
Sample.js
function MyUserController ($scope) {
$scope.name = 'World'
$scope.sayHello = function() {
$scope.greeting = 'Hello ' + $scope.name + '!';
};
}
 
Here, in the example above, MyUserController is a function defined in sample.js and this function has an input parameters $scope. First we will learn about $scope and then try to understand the example above.

6. $scope object
  • Scope is the glue between an application controller and the view.
  • A $scope is an object that ties a view (a DOM element) to the controller.
  • In the Model-View-Controller structure, this $scope object becomes the model.
  • The $scope is just a JavaScript object. Both the controller and the view have access to the $scope so it can be used for communication between the two. 
scope object
 
7. Returning to point 5.
The following is the screen that will be rendered on the DOM.

DOM
 
The following is the description of the example above:
  1. From the left column we are getting "World" in the text box, only due to the $scope binding done by the controller $scope.name = 'World' of the controller and ng-model="name" of the DOM.
    (This is what we can say one way binding)
     
  2. From the right column, here I typed in some text and then clicked on the greet button and I get "Hello World....Binding test!" by the DOM. It is due to declaring {{ greeting }} by the DOM (it is an expression) and the $scope.greeting = 'Hello ' + $scope.name + '!' at MyUserController function.
     
  3. Here we have two-way binding using $scope.name and ng-model="name" defined in the DOM and the Controller as well. We got a default value in the text box when the DOM is loaded and are getting the updated value of username when we click on the button.
8. Filters

Filters allow formatting the data to be displayed on the DOM. Filters are invoked in the HTML with the | (pipe) character inside expressions {{ }}.
 
Few examples
Filter
Filter with Expression
Output at DOM
Currency{{ 123 | currency }} $123.00
Currency{{ 456 | currency:'USD $' }}USD $456.00
Date{{ today | date:'MMM d, y' }}Nov 20, 2013
Number{{ 1234567890 | number }}1,234,567,890
Uppercase{{ "csharp" | uppercase }}CSHARP
String{{ ['Ari', 'Likes', 'To']  | filter:'e' }}Likes
References 


http://www.c-sharpcorner.com/UploadFile/deveshomar/basics-of-angularjs/


Introduction to AngularJS

Controller must be responsible for binding model data to views using $scope. It does not contain logic to fetch the data or manipulating it.
Controller is a javascript function . it contains data .it specifies the behavior.it should contain only the business logic needed for a single view.



Factories

Syntax: module.factory('factoryName', function);

Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to module.factory.

Usage: Could be useful for returning a ‘class’ function that can then be new’ed to create instances.
  
var app = angular.module('myApp', []);

// Factory
app.factory('testFactory', function(){
    return {
        sayHello: function(text){
            return "Factory says \"Hello " + text + "\"";
        }
    }             
});

// AngularJS Controller that uses the factory
function HelloCtrl($scope, testFactory)
{
    $scope.fromFactory = testFactory.sayHello("World");
}


 http://blog.manishchhabra.com/2013/09/angularjs-service-vs-factory-with-example/

http://www.codeproject.com/Articles/737030/A-basic-SPA-application-using-AngularJS-WebAPI-and
http://www.codeproject.com/Articles/607873/Extending-HTML-with-AngularJS-Directives
http://theprofessionalspoint.blogspot.com/2014/02/basic-angularjs-interview-questions-and.html
http://www.c-sharpcorner.com/UploadFile/deveshomar/basics-of-angularjs/

No comments:

Post a Comment