Translate

Thursday 18 June 2015

AngularJS Concepts And Examples Or AngularJs Examples


AngularJS Sessions
Introduction to AJS concepts

è Two way Data Binding
è MVW pattern (Model View Whatever)
è Template
è Custom –directive (Reusable components, Custom markup)
è REST-friendly
è Deep  linking (Setup a link for any dynamic pages)
è Form Validation
è Server Communication
è Localization
è Dependency injection
è Full testing environment (Both Unit and E2E)

Directives:
Angular comes with a set of these directives built-in, like ngBind, ngClass and ngModel. Much like you create controllers and services, you can create your own directives for Angular to use. When Angular bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements.
è The ng-app directive initializes an AngularJS application.
è The ng-init directive initializes application data.
è The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
Example:
<div ng-app="" ng-init="firstName='ABC'">
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>

Output:
 Name:    ABC
 You wrote: ABC

Built-In Directive:
Most useful directives in angularJS:
è ng-app="plaintext"
è ng-controller="plaintext"
è ng-init="expression"
è ng-model="expression"
è ng-include="string"|<ng-include src="string" onload="expression" autoscroll="expression">
è ng-repeat="([key,] value) in object|array"
è ng-hide|show="boolean"
è ng-submit="expression"
è ng-view|<ng-view>
è ng-bind[-html-unsafe]="expression"

Custom Directive: You can create your own directive to use in angularJS.

è Element directives
è Attribute directives
è CSS class directives
è Comment directives
Example:
myapp.directive('userdirective ', function() {
    var directive = {};
    directive.restrict = 'E';
    directive.template = "User : {{user.firstName}} {{user.lastName}}";
    directive.scope = {
        user : "=user"
   }
    return directive;
});


Html Page:


<userdirective user="Ananda"></userdirective >
<userdirective user="Babu"></userdirective >


Filters:

Filters are used for formatting data displayed to the user.
{{ expression [| filter_name[:parameter_value] ... ] }}

è amount | currency[:symbol]: Formats a number as a currency (ie $1,234.56).
è date | date[:format]
è array | filter:expression: Selects a subset of items from array. Expression takes strin­g|O­bje­ct|­fun­cti­on()
è data | json : Convert a JavaScript object into JSON string.
è array | limitTo:limit : Creates a new array containing only a specified number of elements in an array.
è text | linky 1: Finds links in text input and turns them into html links.
è string | lowercase : Converts string to lowercase.
è number | number[:fractionSize] : Formats a number as text. If the input is not a number an empty string is returned.
è array | orderBy:predicate[:reverse] : Predicate is functi­on(­*)|­str­ing­|Array. Reverse is Boolean
è string | uppercase : Converts string to uppercase.

Example:

<script>
var app=angular.module("myApp",[]);
app.controller("mtCtrl",fuction($scope){
$scope.firstName ='abc';
$scope.lastName ='ABC';
$scope.quantity=10;
$scope.price=100;
$scope.names=['Anand','Moula','Siva'];
$scope.country=['US','UK','India'];
});
</script>
<div ng-app="myApp" ng-controller="myCtrl">
<p>The name is {{ firstName | uppercase }}</p>
<p>The name is {{ lastName | lowercase }}</p>
<input type="number" ng-model="quantity">
<input type="number" ng-model="price">
<p>Total = {{ (quantity * price) | currency }}</p>
<ul>
                                <li ng-repeat="x in names | orderBy:'country'">
                                                {{ x.name + ', ' + x.country }}
                                </li>
</ul>
<p><input type="text" ng-model="test"></p>
<ul>
                                 <li ng-repeat="x in names | filter:test | orderBy:'country'">
                                                 {{ (x.name | uppercase) + ', ' + x.country }}
                                </li>
</ul>
</div>

Data Binding:
Data-binding in Angular apps is the automatic synchronization of data between the model and view components
   


Views, Controllers & Scope

Views:
AngularJS supports Single Page Application via multiple views on a single page. To do this AngularJS has provided ng-view and ng-template directives and $routeProvider services.
ng-view: ng-view tag simply creates a place holder where a corresponding view (html or ng-template view) can be placed based on the configuration.
Example:

<div ng-app="mainApp”>
    <div ng-view></div>
</div>   


Controller: The ngController directive attaches a controller class to the view. The class contains business logic behind the application to decorate the scope with functions and values.
Example:
<div ng-app="" ng-controller="myController">
...
</div>


Scope:
It is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimics the DOM structure of the application. Scopes can watch expressions and propagate events.
Example:
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
  $scope.username = 'World';
  $scope.sayHello = function() {
    $scope.greeting = 'Hello ' + $scope.username + '!';
  };
}]);
<div ng-controller="MyController">
  Your name:
    <input type="text" ng-model="username">
    <button ng-click='sayHello()'>Click</button>
  <hr> {{greeting}}
</div>


Modules, Routes, Factories & Services
Module:
 You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc.
è  An AngularJS module defines an application.
è  A module is a container for the different parts of an application.
è  All application controllers should belong to a module.

Example:

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
 $scope.firstName = “Anand";
$scope.lastName = "Moula";
});
</script>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>


Routes:
The ngRoute module provides routing and deep linking services and directives for angular apps.
AngularJS routes enable you to create different URLs for different content in your application. Having different URLs for different content enables the user to bookmark URLs to specific content,  and send those URLs to friends etc. In AngularJS each such bookmarkable URL is called a route.
Example:
    Views: home.cshtml, about.cshtml, contact.cshtml
<!-- home.cshtml -->
    <div class="cssclass text-center">
        <h1>Home Page</h1>
        <p>{{ message }}</p>
    </div>

<!-- about.cshtml -->
    <div class=" cssclass text-center">
        <h1>About Page</h1>
        <p>{{ message }}</p>
    </div>

<!-- contact.cshtml -->
    <div class=" cssclass text-center">
        <h1>Contact Page</h1>
        <p>{{ message }}</p>
    </div>


// script.js
    var myApp = angular.module('myApp', ['ngRoute']);
    myApp.config(function($routeProvider) {
        $routeProvider .when('/', {
                templateUrl : 'pages/home.cshtml',
                controller  : 'mainController'
            })
            // route for the about page
            .when('/about', {
                templateUrl : 'pages/about.cshtml',
                controller  : 'aboutController'
            })
            // route for the contact page
            .when('/contact', {
                templateUrl : 'pages/contact.cshtml',
                controller  : 'contactController'
            });
    });

    myApp.controller('mainController', function($scope) {       
        $scope.message = 'Everyone come and see how good I look!';
    });

    myApp.controller('aboutController', function($scope) {
        $scope.message = 'Look! I am an about page.';
    });

    myApp.controller('contactController', function($scope) {
        $scope.message = 'Contact us! Jagan. This is just a demo.';
    });

The when() method takes a path and a route as parameters. The path is a part of the URL after the # symbol. The route contains two properties named templateUrl andcontroller. The templateUrl property tells which HTML template AngularJS should load and display inside the div with the ngView directive. The controller property tells which controllers should be used with the HTML template.
When the application is loaded, the path is matched against the part of the URL after the # symbol. If no route paths matches the given URL the browser will be redirected to the path specified in the otherwise() function.
Factories:
A factory is a simple function which allows you to add some logic before creating the object. It returns the created object. When you’re using a Factory you create an object, add properties to it, then return that same object. When you pass this service into your controller, those properties on the object will now be available in that controller through your factory.

Services:

When you’re using Service, it’s instantiated with the ‘new’ keyword. Because of that, you’ll add properties to ‘this’ and the service will return ‘this’. When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service.
Example:   Factory and Services

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

app.service('helloWorldService', function(){
    this.hello = function() {
        return "Hello World";
    };
});

app.factory('helloWorldFactory', function(){
    return {
        hello: function() {
            return "Hello World";
        }
    }
});

Providers:
Providers are the only service you can pass into your .config() function. Use a provider when you want to provide module-wide configuration for your service object before making it available.
Example:
var app = angular.module("app",[]);
app.config(function ($provide) {
  $provide.factory("game", function () {
    return {
      title: "StarCraft"
    };
 });
});
app.controller("AppCtrl", function ($scope, game) {
  $scope.title = game.title;
});

Dependency Injection:
Dependency injection is one of AngularJS's best patterns. It makes testing much simpler, as well as making it more clear upon which any particular object depends. AngularJS is very flexible on how things can be injected. The simplest version requires just passing the name of the dependency into the function for the module:              
Example :
var app = angular.module('app',[]);
app.controller('MainCtrl', function($scope, $timeout){
    $timeout(function(){
        console.log($scope);
    }, 1000);
});
  
Localization:
A locale is a specific geographical, political, or cultural region. The most commonly used locale ID consists of two parts: language code and country code. For example, en-US, en-AU, and zh-CN are all valid locale IDs that have both language codes and country codes.
Example:     <script src="l10n/angular-locale_en-in.js"></script>   -- This is for India Locale
                      <script src="l10n/angular-locale_en-us.js"></script>   --This is for US Locale


No comments:

Post a Comment