Friday, June 27, 2014

Angular JS

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. It is MVC framework for client side. It avoids DOM manupulation like JQuery.

The ng-app attribute represents an Angular directive named ngApp (Angular uses spinal-case for its custom attributes andcamelCase for the corresponding directives which implement them). This directive is used to flag the html element that Angular should consider to be the root element of our application. This gives application developers the freedom to tell Angular if the entire html page or only a portion of it should be treated as the Angular application.

Angular expression is a JavaScript-like code snippet that is evaluated by Angular in the context of the current model scope, rather than within the scope of the global context (window).


Angular Expressions vs. JavaScript Expressions

Angular expressions are like JavaScript expressions with the following differences:
  • Context: JavaScript expressions are evaluated against the global window. In Angular, expressions are evaluated against a scopeobject.
  • Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In Angular, expression evaluation is forgiving to undefined and null.
  • No Control Flow Statements: you cannot use the following in an Angular expression: conditionals, loops, or exceptions.
  • Filters: You can use filters within expressions to format data before displaying it.
If you want to run more complex JavaScript code, you should make it a controller method and call the method from your view. If you want toeval() an Angular expression yourself, use the $eval() method.

Bootstrapping AngularJS apps

Angular initializes automatically upon DOMContentLoaded event or when theangular.js script is evaluated if at that time document.readyState is set to'complete'. At this point Angular looks for the ng-app directive which designates your application root. If the ng-app directive is found then Angular will: 
  • load the module associated with the directive.
  • create the application injector
  • compile the DOM treating the ng-app directive as the root of the compilation. This allows you to tell it to treat only a portion of the DOM as an Angular application.

Compiler

Compiler is an Angular service which traverses the DOM looking for attributes. The compilation process happens in two phases.
  1. Compile: traverse the DOM and collect all of the directives. The result is a linking function.
  2. Link: combine the directives with a scope and produce a live view. Any changes in the scope model are reflected in the view, and any user interactions with the view are reflected in the scope model. This makes the scope model the single source of truth.
Directive
A directive is a behavior which should be triggered when specific HTML constructs are encountered during the compilation process. The directives can be placed in element names, attributes, class names, as well as comments. Here are some equivalent examples of invoking the ng-bind directive.
A directive is just a function which executes when the compiler encounters it in the DOM. See directive API for in-depth documentation on how to write directives.

How directives are compiled

It's important to note that Angular operates on DOM nodes rather than strings. Usually, you don't notice this restriction because when a page loads, the web browser parses HTML into the DOM automatically.
HTML compilation happens in three phases:
  1. $compile traverses the DOM and matches directives.
    If the compiler finds that an element matches a directive, then the directive is added to the list of directives that match the DOM element. A single element may match multiple directives.
  2. Once all directives matching a DOM element have been identified, the compiler sorts the directives by their priority.
    Each directive's compile functions are executed. Each compile function has a chance to modify the DOM. Each compilefunction returns a link function. These functions are composed into a "combined" link function, which invokes each directive's returned link function.
  3. $compile links the template with the scope by calling the combined linking function from the previous step. This in turn will call the linking function of the individual directives, registering listeners on the elements and setting up $watchs with the scope as each directive is configured to do.

Module

You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc
Most applications have a main method that instantiates and wires together the different parts of the application.
Angular apps don't have a main method. Instead modules declaratively specify how an application should be bootstrapped. There are several advantages to this approach:
  • The declarative process is easier to understand.
  • You can package code as reusable modules.
  • The modules can be loaded in any order (or even in parallel) because modules delay execution.
  • Unit tests only have to load relevant modules, which keeps them fast.
  • End-to-end tests can use modules to override configuration.

Scope

A scope can be seen as the glue which allows the template, model and controller to work together. Angular uses scopes, along with the information contained in the template, data model, and controller, to keep models and views separate, but in sync. Any changes made to the model are reflected in the view; any changes that occur in the view are reflected in the model.
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. Scopes can watch expressions and propagate events.
  • Scopes provide APIs ($watch) to observe model mutations.
  • Scopes provide APIs ($apply) to propagate any model changes through the system into the view from outside of the "Angular realm" (controllers, services, Angular event handlers).
  • Scope 2 type - child scope, isolated scope
During the template linking phase the directives set up $watch expressions on the scope. The $watch allows the directives to be notified of property changes, which allows the directive to render the updated value to the DOM.

Isolate scope as name suggests will not inherit from parent scope. Useful for directives to have its own value for multiple instances.

Controller


In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope.
When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be available as an injectable parameter to the Controller's constructor function as $scope.
Use controllers to:
  • Set up the initial state of the $scope object.
  • Add behavior to the $scope object.

Service components in ng

NameDescription
$anchorScroll
When called, it checks current value of $location.hash() and scrolls to the related element, according to rules specified in Html5 spec.
$animate
The $animate service provides rudimentary DOM manipulation functions to insert, remove and move elements within the DOM, as well as adding and removing classes. This service is the core service used by the ngAnimate $animator service which provides high-level animation hooks for CSS and JavaScript.
$cacheFactory
Factory that constructs Cache objects and gives access to them.
$templateCache
The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a script tag, or by consuming the $templateCache service directly.
$compile
Compiles an HTML string or DOM into a template and produces a template function, which can then be used to linkscope and the template together.
$controller
$controller service is responsible for instantiating controllers.
$document
jQuery or jqLite wrapper for the browser's window.document object.
$exceptionHandler
Any uncaught exception in angular expressions is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console.
$filter
Filters are used for formatting data displayed to the user.
$http
The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
$httpBackend
HTTP backend used by the service that delegates to XMLHttpRequest object or JSONP and deals with browser incompatibilities.
$interpolate
Compiles a string with markup into an interpolation function. This service is used by the HTML $compile service for data binding. See $interpolateProvider for configuring the interpolation markup.
$interval
Angular's wrapper for window.setInterval. The fn function is executed every delay milliseconds.
$locale
$locale service provides localization rules for various Angular components. As of right now the only public api is:
$location
The $location service parses the URL in the browser address bar (based on the window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
$log
Simple service for logging. Default implementation safely writes the message into the browser's console (if present).
$parse
Converts Angular expression into a function.
$q
A promise/deferred implementation inspired by Kris Kowal's Q.
$rootElement
The root element of Angular application. This is either the element where ngApp was declared or the element passed into angular.bootstrap. The element represent the root element of application. It is also the location where the applications $injector service gets published, it can be retrieved using $rootElement.injector().
$rootScope
Every application has a single root scope. All other scopes are descendant scopes of the root scope. Scopes provide separation between the model and the view, via a mechanism for watching the model for changes. They also provide an event emission/broadcast and subscription facility. See the developer guide on scopes.
$sceDelegate
$sceDelegate is a service that is used by the $sce service to provide Strict Contextual Escaping (SCE) services to AngularJS.
$sce
$sce is a service that provides Strict Contextual Escaping services to AngularJS.
$timeout
Angular's wrapper for window.setTimeout. The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service.
$window
A reference to the browser's window object. While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In angular we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.