Saturday 31 October 2015

Basics : Angularjs

What is Angular JS ?


Angular JS is JavaScript framework to create SPA applications. It simplifies complex javascript DOM manipulation code by providing declarative tags. This provides a clean separation between DOM manipulation logic and the HTML view.

For example below is a simple Angular code which helps us to display textbox data in the DIV tag when the user types in the textbox.


<input type=text ng-model="name">
<div>


    Current user's name: {{name}}

Is AngularJS a library, framework, plugin or a browser extension?

AngularJS fits the definition of a framework the best, even though it's much more lightweight than a typical framework and that's why many confuse it with a library.

AngularJS is 100% JavaScript, 100% client side and compatible with both desktop and mobile browsers. So it's definitely not a plugin or some other native browser extension.

What are the key features of AngularJS?

Scope

Scope refers to the application model, it acts like glue between application controller and the view. The job of the Scope is to detect changes to model objects and create an execution context for expressions. There is one root scope for the application (ng-app) with hierarchical children scopes. It marshals the model to the view and forwards events to the controller.
   Actually it is a ViewModel. that works as a mediater between View and Controller to bind and View Data.

Controller

 AJs controllers control the data of AngularJS Applications.they are like regular javascript object. The Controller is responsible for construction of the model and connects it to the view (HTML). The scope sits between the controller and the view. Controllers should be straightforward and simply contain the business logic needed for a view. Generally you want thin controllers and rich services. Controllers can be nested and handle inheritance. The big difference in AngularJS from the other JavaScript frameworks is there is no DOM manipulation in controllers. It is something to unlearn when developing in AngularJS.

Model

In AngularJS, a Model is simply a JavaScript object. No need to extend anything or create any structure. This allows for nested models  - something that Backbone doesn’t do out-of-the-box.

View

The View is based on DOM objects, not on strings. The view is the HTML. HTML is declarative – well suited for UI design. The View should not contain any functional behavior. The flexibility here is to allow for multiple views per Controller.

Services

The Services in AngularJS are singletons that perform common tasks for web applications. If you need to share common functionality between Controllers, then use Services. Built-in AngularJS, Services start with a $. There are several ways to build a service: Service API, Factory API, or the $provide API.

Data Binding

Data Binding in AngularJS is a two-way binding between the View and the Model. Automatic synchronizing between views and data models makes this really easy (and straightforward) to use. Updating the model is reflected in View without any explicit JavaScript code to bind them together, or to add event listeners to reflect data changes.

Directives

AngularJS allows you to use Directives to transform the DOM or to create new behavior. A directive allows you to extend the HTML vocabulary in a declarative fashion. The ‘ng’ prefix stands for built-in AngularJS directives. The App (ng-app), Model (ng-model), the Controller (ng-controller), etc. are built into the framework. AngularJS allows for building your own directives. Building directives is not extremely difficult, but not easy either. There are different things that can be done with them. Please check out AngularJS’s documentation on directives.

Different types of directives are
Element directives
Attribute directives
CSS class directives
Comment directives

Filters

The Filters in AngularJS perform data transformation. They can be used to do formatting (like I did in my Directives example with padding zeros), or they can be used to do filter results (think search).

Validation

AngularJS has some built-in validation around HTML5 input variables (text, number, URL, email, radio, checkbox) and some directives (required, pattern, minlength, maxlength, min, max). If you want to create your own validation, it is just as simple as creating a directive to perform your validation.

Testable

Testing is a big concern for enterprise applications. There are several different ways to write and run tests against JavaScript code, thus against AngularJS. The developers at AngularJS advocate using Jasmine tests ran using Testacular. I have found this method of testing very straightforward and, while writing tests may not be the most enjoyable, it is just as importable as any other piece of developing an application.

What is a scope in AngularJS?

scope is an object that refers to the application model. It is the glue between application controller and the view. Both the controllers and directives have reference to the scope, but not with each other. It is an execution context for expressions and arranged in hierarchical structure. Scopes can watch expressions and propagate events.

What is Routing?  How to Create it in AngularJS?

AngularJS routes enable you to create different URLs for different content in your application. for routing you have to include angular-route.min.js file.


// create the module and name it scotchApp
var scotchApp = angular.module('scotchApp', ['ngRoute']);
// configure our routes
scotchApp.config(function ($routeProvider) {
    $routeProvider
   // route for the home page
      .when('/', {
          templateUrl: 'pages/home.html',
          controller: 'mainController'
      })
  // route for the about page
  .when('/about', {
      templateUrl: 'pages/about.html',
      controller: 'aboutController'
  })

});

If you’re using animations you’ll need angular-animation.js and also need to reference the appropriate
module:
var scotchApp = angular.module('scotchApp', ['ngRoute''ngAnimate']);

How will you initialize a select box with options on page load?

Use the ng-init directive.
<div ng-controller="apps/dashboard/account" ng-switch on="!!accounts" ng-init="loadData()">

What is Module?  How to Create it in AngularJS?
You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc.angular.module is used to configure the $injector.

// declare a module

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

Directives- are the attribute provided by the angularjs.
               ex: ng-app, ng-init, ng-model, ng-bind
ng-init ->  initialize application data.
              ex:-  ng-init="name='suraj'"
ng-model -> bind application data(model property) to html element.
               ex:- ng-model="name"
ng-bind -> bind application variable name with html control.
              ex:- ng-bind="name" .  it's jst like expressions {{}}

AngularJS Expression - written inside double braces. {{name}}. it binds data to html the same way as the ng-bind directive.

How will you show/hide buttons and enable/disable buttons conditionally?

Using the ng-show and ng-disabled directives.
<div class="dataControlPanel"
     ng-show="accounts.releasePortfolios">

    <div class="dataControlButtons">
        <button class="btn btn-primary btn-small"
                ng-click="saveComments()" ng-disabled="disableSaveButton">
            Save
        </button>
        <button class="btn btn-primary btn-small"
                ng-click="releaseRun()" ng-disabled="disableReleaseButton">
            Release
        </button>
    </div>

</div>

How will you loop through a collection and list each item?

Using the ng-repeat directive.


<table class="table table-bordered table-striped table-hover table-fixed-head portal-data-table">
    <thead>
        <tr>
            <th>account</th>
            <th>Difference</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="account in acounts">
            <td width="40%">{{account.accountCode}}</td>
         <td width="30%" style="text-alignright">{{account.difference | currency: ""}}</td>
            <td width="30%">
                <div ng-switch on="account.status">
                    <div ng-switch-when="AMBER">
                        <img class="statusIcon"
                             src='apps/dashboard/amber-dot.jpg' />
                    </div>
                    <div ng-switch-when="GREEN">
                        <img class="statusIcon" src='apps/dashboard/green-dot.jpg' />
                    </div>
                    <div ng-switch-when="RED">
                        <img class="statusIcon" src='apps/dashboard/red-dot.jpg' />
                    </div>
                </div>
            </td>
        </tr>
    </tbody>

</table>

How to enable and disable buttons with using condition?


<div ng-app="myapp">
    <div ng-controller="myScope">
        First Name :  <input type="text" ng-model="fName" /><br>
        Last Name :  <input type="text" ng-model="lName" /><br>
        <button ng-disabled="!fName || !lName">Submit</button>
    </div>
</div>

<script>
    var $scope;
    var app = angular.module('myapp', []);
    function myScope($scope) {
    }

</script>

How to bind selection box with options in the angular js?
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.js"></script>
</head>
<script>
    angular.module('SelectBoxWithOptions', [])
 .controller('Controller', ['$scope''$http'function ($scope, $http) {
     $http.get('CountriesCitiesList.json')
.success(function (data, status, headers, config) {
    $scope.locations = data;
});
 }]);

</script>
<body data-ng-app="SelectBoxWithOptions">
    <h1>Select box with options</h1>
    <div class="ng-controller" data-ng-controller="Controller">
        <label>Countries</label>
        <select data-ng-model="countries" data-ng-options="loc.country for loc in locations">
            <option value="">Please chose country</option>
        </select>
        <label>Cities</label>
        <select data-ng-model='city' data-ng-options='c for c in countries.cities'>
            <option value="">Please chose city</option>
        </select>
    </div>
</body>

</html>

CountriesCitiesList.json is the next file used in $http.get('CountriesCitiesList.json') for display list.

    [
 {
     "code": 1,
     "country""Germany",
     "cities": [
       "Berlin",
       "Munich"
     ]
 },
 {
     "code": 2,
     "country""Italy",
     "cities": [
       "Rome",
       "Venice"
     ]
 },
 {
     "code": 3,
     "country""United Kingdom",
     "cities": [
       "London",
       "Manchester"
     ]
 }
]



 How to display images based on the status(A, B, and C) in angular js?
<div ng-switch on="account.status">

    <div ng-switch-when="A">
        <img class="statusIcon" src='apps/index/Adot.png' />
    </div>
    <div ng-switch-when="B">
        <img class="statusIcon" src='apps/index/Bdot.png' />
    </div>
    <div ng-switch-when="C">
        <img class="statusIcon" src='apps/index/Cdot.png' />
    </div>

</div>

Mention what are the advantages of using Angular.js framework ?

Advantages of using Angular.js as framework are

Supports two way data-binding
Supports MVC pattern
Support static template and angular template
Can add custom directive
Supports REST full services
Supports form validations
Support both client and server communication
Support dependency injection
Applying Animations
Event Handlers

What is Service?
the services are singleton objects or functions that carry out specific tasks. It holds some business logic.

What is The difference between factory and service in Angular JS ?
The difference between factory and service is just like the difference between a function and an object. The difference between the two is just the way in which they create the object that goes and gets  the data.  That’s really all two is to it.  
 (-  With the factory you actually create an object inside of the factory and return it.  
 (- With the service you just have a standard function that uses the this keyword to define 
function.  
 Click here to know more Click here

What is $Watch() ?

The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function:

A value function
A listener function

Here is an example:
$scope.$watch(function() {},
              function() {}
             );
The first function is the value function and the second function is the listener function.


The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time. That way AngularJS can determine if the value has changed. Here is an example:
$scope.$watch(function(scope) { return scope.data.myVar },
              function() {}
             );
This example valule function returns the $scope variable scope.data.myVar. If the value of this variable changes, a different value will be returned, and AngularJS will call the listener function.


What is $Digest() ?


The $scope.$digest() function iterates through all the watches in the $scope object, and its child $scope objects (if it has any). When $digest() iterates over the watches, it calls the value function for each watch. If the value returned by the value function is different than the value it returned the last time it was called, the listener function for that watch is called.

to know more about $watch and $digest click here

$q - A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

1 comment:

1 comment:

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...