Angular JS 1.5

AngularJS is an open source JavaScript MVC framework for web application or web sites. It extends the HTML and makes it dynamic. AngularJS can be used to create Single Page Applications.It extends the ability of HTML by adding built-in attributes and components and also provides an ability to create custom attributes using simple JavaScript.





$scope.apply() and $scope.digest()
Reference:https://www.sitepoint.com/understanding-angulars-apply-digest/
https://www.tutlane.com/tutorial/angularjs/angularjs-watch-digest-and-apply-functions


AngularJs $apply() function

In angularjs the $apply() function is used to evaluate expressions outside of angularjs context (like browser DOM events, setTimeout, XHR or third party libraries). Generally in angularjs once $apply() function execution finishes forcefully it will call $digest() function to update all data bindings.

Following are the differences between $apply and $digest() functions in angularjs.

  1. The $apply() and $digest() methods are used to update the model properties forcefully.
  2. The $digest() method evaluate watchers for current scope but $apply() method is used to evaluate watchers forroot scope that means it's for all scopes.
$digest()
In angularjs if $digest() function found any change in watch list variables then corresponding event listener functions will call and update those values in view with new values.

AngularJS $watch() Function


In angularjs $watch() function is used to watch the changes of variables in the $scope object. Generally in angularjs the $watch() function will be created internally to handle variable changes in application. The $watch() function will be useful whenever we want to create custom watch for any events.

ng  :The prefix ng stands for "Angular;" all of the built-in directives that ship with Angular use that prefix. Similarly, it is recommended that you do not use the ng prefix on your own directives in order to avoid possible name collisions in future versions of Angular. 


ng-app :The ng-app directive is a starting point of AngularJS Application. It initializes the AngularJS framework automatically. AngularJS framework will first check for ng-app directive in a HTML document after the entire document is loaded and if ng-app is found, it bootstraps itself and compiles the HTML template.Use this directive to auto-bootstrap an AngularJS application.The ng-app directive can also specify an application module name.

we can also initialize AngularJS manually without using ng-app directive.

<body> <div> {{2/2}}  </div>
    <div>    {{5/2}}   <div> {{10/2}} </div>   
    </div>
<script>       
     angular.element(document).ready(function () {
         angular.bootstrap(document);
     });


</script>





AngularJS expression is like JavaScript expression surrounded with braces - {{ expression }}. AngularJS evaluates the specified expression and binds the result data to HTML.

AngularJS expression can contain variables declared via ng-init directive. The ng-init directive is used to declare AngularJS application variables of any data type.       ng-init="greet='Hello World!'"

  1. AngularJS expression cannot contain conditions, loops, exceptions or regular expressions e.g. if-else, ternary, for loop, while loop etc.
  2. AngularJS expression cannot declare functions.
  3. AngularJS expression cannot contain comma or void.
  4. AngularJS expression cannot contain return keyword.

AngularJS Directives :

Directives are markers on a DOM element that tell AngularJS to attach a specified behavior to that DOM element or even transform the DOM element and its children. In short, it extends the HTML.

Directive
Description
ng-app
Auto bootstrap AngularJS application.The ng-app directive initializes AngularJS 
ng-init
Initializes AngularJS variables
ng-model
Binds HTML control's value to a property on the $scope object.
ng-controller
Attaches the controller of MVC to the view.
ng-bind
Replaces the value of HTML control with the value of specified AngularJS expression.
ng-repeat
Repeats HTML template once per each item in the specified collection.
ng-show
Display HTML element based on the value of the specified expression.
ng-readonly
Makes HTML element read-only based on the value of the specified expression.
ng-disabled
Sets the disable attribute on the HTML element if specified expression evaluates to true.
ng-if
Removes or recreates HTML element based on an expression.
ng-click
Specifies custom behavior when an element is clicked.

ng-model:

The ng-model directive is used for two-way data binding in AngularJS. It binds <input>, <select> or <textarea> elements to a specified property on the $scope object. So, the value of the element will be the value of a property .
Note : Variables initialized in ng-init are different from the properties defined using ng-model directive. The variables initialized in ng-init are not attached to $scope object whereas ng-model properties are attached to $scope object.
ng-bind:
The ng-bind directive binds the model property declared via $scope or ng-model directive or the result of an expression to the HTML element. It also updates an element if the value of an expression changes.
'ng-bind' is an angular directive used for achieving one-way data binding.




Two-way data binding
Two-way data binding in AngularJS means binding data from Model to View and vice versa (Data flows from the Scope/Controller to the View and from the View to the scope/controller). 'ng-model' is an angular directive used for achieving two-way data binding. 
One-way data binding
One-way data binding in AngularJS means binding data from Model to View (Data flows from the scope/controller to the view). 'ng-bind' is an angular directive used for achieving one-way data binding. After the binding, any modifications to that model from the scope/controller will be automatically propagated to the view regardless of whether the view is asking for the updated data. No propagation happens for any change to the model from the view to the controller.
One-time data binding

As its name suggests, the binding happens only once, ie, in the first digest cycle. One-time binding allows for a model or view to be updated ONCE from the value set by the controller upon the first digest cycle. As of AngularJS 1.3, you can use the "::" token to create one-time data bindings. These are bindings that deregister their own $watch() functions once the value has stabilized (which basically means the value is defined).
Difference b/w ng-bind and {{}}
Visibility:

While your angularjs is bootstrapping, the user might see your placed brackets in the html. This can be handled with ng-cloak
Performance:
The {{}} is much slower.
This ng-bind is a directive and will place a watcher on the passed variable. So the ng-bind will only apply, when the passed value does actually change.

The brackets on the other hand will be dirty checked and refreshed in every $digest, even if it's not necessary.
Binding:
{{}} use two way binding

ng-bind use one way binding.


ng-if :

The ng-if directive creates or removes an HTML element based on the Boolean value returned from the specified expression. If an expression returns true then it recreates an element otherwise removes an element from the HTML document.

ng-readonly

The ng-readonly directive makes an HTML element read-only, based on the Boolean value returned from the specified expression. If an expression returns true then the element will become read-only, otherwise not.

ng-disabled

The ng-disabled directive disables an HTML element, based on the Boolean value returned from the specified expression. If an expression returns true the element will be disabled, otherwise not.

Directive Syntax :

AngularJS directives can be applied to DOM elements in many ways. It is not mandatory to use ng- syntax only.
Directive can start with x- or data-, for example ng-model directive can be written as data-ng-model or x-ng-model.
Also, the - in the directive can be replaced with : or _ or both. For example, ng-model can be written as ng_model or ng:model. It can also be a mix with data- or x-.

AngularJS Controller

The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object.
You can attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviours to HTML elements. The $scope object is a glue between the controller and HTML.

The ng-controller directive is used to specify a controller in HTML element, which will add behavior or maintain the data in that HTML element and its child elements.
<body ng-app="myNgApp">
<div ng-controller="myController">
{{message}}
</div>
<script>
var ngApp = angular.module('myNgApp', []);
ngApp.controller('myController', function ($scope) {
$scope.message = "Hello World!";
});
</script>
</body>
Controller Syntax for Minification:
<script>
var ngApp = angular.module('myNgApp', []);
ngApp.controller('myController', ['$scope', function ($scope) {
$scope.message = "Hello World!";
}]);
</script>

Scope in AngularJS

The $scope in an AngularJS is a built-in object, which contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it.
The $scope is glue between a controller and view (HTML). It transfers data from the controller to view and vice-versa.
AngularJS creates and injects a different $scope object to each controller in an application. So, the data and methods attached to $scope inside one controller cannot be accessed in another controller. With the nested controller, child controller will inherit the parent controller's scope object.

Reference :https://www.tutorialsteacher.com/angularjs

$rootScope

An AngularJS application has a single $rootScope. All the other $scope objects are child objects.The properties and methods attached to $rootScope will be available to all the controllers.
What is the difference between rootScope and scope?
The $scope is created with ng-controller while $rootscope is created with ng-app . The main difference is the availability of the property assigned with the object. A property assigned with $scope cannot be used outside the controller in which it is defined whereas a property assigned with $rootScope can be used anywhere.



The $scope object contains various methods. The following table lists important methods of $scope object.

thod
Description
$new()
Creates new child scope.
$watch()
Register a callback to be executed whenever model property changes.
$watchGroup()
Register a callback to be executed whenever model properties changes. Here, specify an array of properties to be tracked.
$watchCollection()
Register a callback to be executed whenever model object or array property changes.
$digest()
Processes all of the watchers of the current scope and its children. 
$destroy()
Removes the current scope (and all of its children) from the parent scope.
$eval()
Executes the expression on the current scope and returns the result.
$apply()
Executes an expression in angular outside the angular framework.
$on()
Register a callback for an event.
$emit()
Dispatches the specified event upwards till $rootScope.
$broadcast()
Dispatches the specified event downwards to all child scopes.
$watch
Angular scope object includes $watch event which will be raised whenever a model property is changed.
$scope.$watch('message', function (newValue, oldValue) {
$scope.newMessage = newValue;
$scope.oldMessage = oldValue;
});

AngularJS Events:

AngularJS includes certain directives which can be used to provide custom behavior on various DOM events, such as click, dblclick, mouseenter etc.

AngularJS Service:

AngularJS services are JavaScript functions for specific tasks, which can be reused throughout the application.
Most AngularJS services interact with the controller, model or custom directives. However, some services interact with view (UI) also for UI specific tasks.
All the Angular services are lazy instantiated and singleton. It means AngularJS framework instantiates a service when an application component depends on it. Also, all the components share the same instance of a service.
The $http service is used to send or receive data from the remote server using browser's XMLHttpRequest or JSONP.
$http is a service as an object. It includes following shortcut methods.
MethodDescription
$http.get()Perform Http GET request.
$http.head()Perform Http HEAD request.
$http.post()Perform Http POST request.
$http.put()Perform Http PUT request.
$http.delete()Perform Http DELETE request.
$http.jsonp()Perform Http JSONP request.
$http.patch()Perform Http PATCH request.

$http.post

The $http.post() method sends Http POST request to the remote server to submit and retrieve the data.
Signature: HttpPromise $http.post(url, dataToSubmit);
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope, $http) {
var onSuccess = function (data, status, headers, config) {
$scope.data = data;
};
var onError = function (data, status, headers, config) {
$scope.error = status;
}
$http.post('/demo/submitData', { myData: 'Hello World!' })
.success(onSuccess)
.error(onError);
});

$log Service

AngularJs includes logging service $log, which logs the messages to the browser's console.The $log service includes different methods to log the error, information, warning or debug information. It can be useful in debugging and auditing.
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($log) {
$log.log('This is log.');
$log.error('This is error.');
$log.info('This is info.');
$log.warn('This is warning.');
$log.debug('This is debugging.');
});

$interval Service

AngularJS includes $interval service which performs the same task as setInterval() method in JavaScript. The $interval is a wrapper for setInterval() method, so that it will be easy to override, remove or mocked for testing.The $interval service executes the specified function on every specified milliseconds duration.
Signature: $interval(fn, delay, [count], [invokeApply], [Pass]);
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope, $interval) {
$scope.counter = 0;
var increaseCounter = function () {
$scope.counter = $scope.counter + 1;
}
});
$interval(increaseCounter, 1000, 10);
//Cancel the interval
var promise = $interval(increaseCounter, 1000);
$scope.cancel = function () {
$interval.cancel(promise);
$scope.counter = "Cancelled!";
};

$window Service

AngularJs includes $window service which refers to the browser window object.In the JavaScript, window is a global object which includes many built-in methods like alert(), prompt() etc.The $window service is a wrapper around window object, so that it will be easy to override, remove or mocked for testing. It is recommended to use $window service in AngularJS instead of global window object directly.
var myApp = angular.module('myApp', []);
myApp.controller("myController", function ($scope, $window) {
$scope.DisplayAlert = function (message) {
$window.alert(message);
}
$scope.DisplayPrompt = function () {
var name = $window.prompt('Enter Your Name');
$window.alert('Hello ' + name);
}
});

Reference :https://www.tutorialsteacher.com/angularjs

AngularJS Filters

AngularJS Filters allow us to format the data to display on UI without changing original format.Filters can be used with an expression or directives using pipe | sign.
{{expression | filterName:parameter }}
Angular includes various filters to format data of different data types. The following table lists important filters.
Filter Name
Description
Number
Formats a numeric data as text with comma and fraction.
Currency
Formats numeric data into specified currency format and fraction.
Date
Formats date to string in specified format.
Uppercase
Converts string to upper case.
Lowercase
Converts string to lower case.
Filter
Filters an array based on specified criteria and returns new array.
orderBy
Sorts an array based on specified predicate expression.
Json
Converts JavaScript object into JSON string
limitTo
Returns new array containing specified number of elements from an existing array.

Number Filter:

amount | number = {{amount | number}} <br />
amount | number:2 = {{amount | number:2}} <br />

Currency Filter

The currency filter formats a number value as a currency. When no currency symbol is provided, default symbol for current locale is used.
Default currency: {{person.salary | currency}} <br />
Custom currency identifier: {{person.salary | currency:'Rs.'}} <br />
No Fraction: {{person.salary | currency:'Rs.':0}} <br />

Date filter

Formats date to string based on the specified format.
Default date: {{person.DOB| date}} <br />
Short date: {{person.DOB| date:'short'}} <br />
Long date: {{person.DOB | date:'longDate'}} <br />
Year: {{person.DOB | date:'yyyy'}} <br />
Default date: Mar 30, 1980
short date: 3/30/80 8:47 AM
long date: March 30, 1980
Year: 1980
Uppercase/lowercase filter
The uppercase filter converts the string to upper case and lowercase filter converts the string to lower case.
Lower case: {{person.firstName + ' ' + person.lastName | lowercase}} <br />
Upper case: {{person.firstName + ' ' + person.lastName | uppercase}}

Filter

Filter selects items from an array based on the specified criteria and returns a new array.
<div ng-controller="myController">
 Enter Name to search: <input type="text" ng-model="searchCriteria" /> <br />   Result: {{myArr | filter:searchCriteria}} 
    </div>

orderBy filter

The orderBy filter sorts an array based on specified expression predicate.
<div ng-controller="myController">
<select ng-model="SortOrder">
<option value="+name">Name (asc)</option>
<option value="-name">Name (dec)</option>
<option value="+phone">Phone (asc)</option>
<option value="-phone">Phone (dec)</option>
</select>
<ul ng-repeat="person in persons | orderBy:SortOrder">
<li>{{person.name}} - {{person.phone}}</li>
</ul>
</div>

ngularJS Modules

A module in AngularJS is a container of the different parts of an application such as controller, service, filters, directives, factories etc. It supports separation of concern using modules.AngularJS stops polluting global scope by containing AngularJS specific functions in a module.

Application Module

An AngularJS application must create a top level application module. This application module can contain other modules, controllers, filters, etc.
 var myApp = angular.module('myApp', []); 

Angular Modules in Separate Files

app.js
var myApp = angular.module("myApp", []);
myController.js
myApp.controller("myController", function ($scope) {
$scope.message = "Hello Angular World!";
});
Multiple Mudule into single application module
var myApplication = angular.module("myApplication", ["mySharedElements"]);

Validation in AngularJS:

Directive
Description
ng-required
Sets required attribute on an input field.
ng-minlength
Sets minlength attribute on an input field.
ng-maxlength
Sets maxlength attribute on an input field. Setting the attribute to a negative or non-numeric value, allows view values of any length.
ng-pattern
Sets pattern validation error key if the ngModel value does not match the specified RegEx expression.
<form name="studentForm" novalidate>
<label for="firstName">First Name: </label> <br />
<input type="text" name="firstName" ng-model="student.firstName" ng-required="true" />
<span ng-show="studentForm.firstName.$touched && studentForm.firstName.$error.required">
First name is required.</span><br /><br />
<label for="lastName">Last Name</label><br />
<input type="text" name="lastName" ng-minlength="3" ng-maxlength="10" ng-model="student.lastName" />
<span ng-show="studentForm.lastName.$touched && studentForm.lastName.$error.minlength">
min 3 chars.</span>
<span ng-show="studentForm.lastName.$touched && studentForm.lastName.$error.maxlength">
Max 10 chars.</span><br /><br />
<label for="dob">Email</label><br />
<input type="email" id="email" ng-model="student.email" name="email" />
<span ng-show="studentForm.email.$touched && studentForm.email.$error.email">
Please enter valid email id.</span><br /><br />
<input type="submit" value="Submit" />
</form>

tate Properties

Angular includes properties which return the state of form and input controls. The state of the form and control changes based on the user's interaction and validation errors. These built-in properties can be accessed using form name or input control name. To check the form status use formName.propertyName, and to check the state of input control, use formName.inputFieldName.propertyName.
Property
Description
$error
$error object contains all the validation attributes applied to the specified element.
$pristine
Returns true if the user has not interacted with control yet else returns false.
$valid
Returns true if the model is valid
$invalid
Returns true if the model is invalid
$dirty
Returns true if user changed the value of model at least once
$touched
Returns true if the user has tabbed out from the control.
$untouched
Returns true if the user has not tabbed out from the control.

AngularJS Validation CSS Classes

CSS Class
Description
ng-valid
Angular will set this CSS class if the input field is valid without errors.
ng-invalid
Angular will set this CSS class if the input does not pass validations.
ng-pristine
Angular will set this CSS class if a user has not interacted with the control yet.
ng-dirty
Angular will set this CSS class if the value of form field has been changed.
ng-touched
Angular will set this CSS class if a user tabbed out from the input control.
ng-untouched
Angular will set this CSS class if a user has not tabbed out from the input control.
ng-submitted
Angular will set this CSS class if the form has been submitted.

Bootstrap CSS Classes for Styling Validation Messages:

Bootstrap CSS Class
Description
has-error
Set this CSS class when a form field becomes invalid based on applied validation attributes.
has-warning
Set this CSS class to display warning for a form field.
has-success
Set this CSS class when a form field becomes valid based on applied validation attributes.

AngularJS Routing:

AngularJS supports SPA using routing module ngRoute. This routing module acts based on the url. When a user requests a specific url, the routing engine captures that url and renders the view based on the defined routing rules.
The angular-route.js includes necessary functions for routing
Apply ng-view directive to <div> or other elements where you want to inject another child view. AngularJS routing module uses ng-view directive to inject another child view where it is defined
we need to configure the routing rules that need to compile before any other module of an application. So, use config() method to configure the routing rules using $routingProvider object.
 $routeProvider.when(path, route) method to configure routing rules
otherwise() method to redirect to base url if user request for the URL other than configured rules.
$routeProvider.when('/', {
templateUrl: '/login.html',
controller: 'loginController'
}).when('/student/:username', {
templateUrl: '/student.html',
controller: 'studentController'
}).otherwise({
redirectTo: "/"
});
 $location.path('/student/' + username)
The $location service parses the URL in the browser address bar (based on window.location) and makes the URL available to your application. Changes to the URL in the address bar are reflected into the $location service and changes to $location are reflected into the browser address bar.

Exception Handling in AngularJS:

AngularJS also includes built-in $exceptionHandler service, which handles uncaught exceptions in the application.
The default implementation of $exceptionHandler service logs the exception into the browser console. You can override this service as per your requirement.
app.config(function ($provide) {
$provide.decorator('$exceptionHandler', function ($delegate) {
return function (exception, cause) {
$delegate(exception, cause);
alert('Error occurred! Please contact admin.');
};
});
});


Module Components
Function
Name
Description
Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key, obj), where value is the value of an object property or an array element, key is the object property key or array element index and obj is the obj itself. Specifying a context for the function is optional.
Extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.extend({}, object1, object2).
Deeply extends the destination object dst by copying own enumerable properties from the srcobject(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.merge({}, object1, object2).
A function that performs no operations. This function can be useful when writing code in the functional style.
function foo(callback) {
  var result = calculateResult();
  (callback || angular.noop)(result);
}
A function that returns its first argument. This function is useful when writing code in the functional style.
Determines if a reference is undefined.
Determines if a reference is defined.
Determines if a reference is an Object. Unlike typeof in JavaScript, nulls are not considered to be objects. Note that JavaScript arrays are objects.
Determines if a reference is a String.
Determines if a reference is a Number.
Determines if a value is a date.
Determines if a reference is an Array.
Determines if a reference is a Function.
Determines if a reference is a DOM element (or wrapped jQuery element).
Creates a deep copy of source, which should be an object or an array. This functions is used internally, mostly in the change-detection code. It is not intended as an all-purpose copy function, and has several limitations (see below).
Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and objects.
Returns a function which calls function fn bound to self (self becomes the this for fn). You can supply optional args that are prebound to the function. This feature is also known as partial application, as distinguished from function currying.
Serializes input into a JSON-formatted string. Properties with leading $$ characters will be stripped since AngularJS uses this notation internally.
Deserializes a JSON string.
Use this function to manually start up AngularJS application.
Use this function to reload the current application with debug information turned on. This takes precedence over a call to $compileProvider.debugInfoEnabled(false).
Creates an injector object that can be used for retrieving services as well as for dependency injection (see dependency injection).
Wraps a raw DOM element or HTML string as a jQuery element.
The angular.module is a global place for creating, registering and retrieving AngularJS modules. All modules (AngularJS core or 3rd party) that should be available to an application must be registered using this mechanism.
Configure several aspects of error handling in AngularJS if used as a setter or return the current configuration if used as a getter. The following options are supported:
Directive
Name
Description
Use this directive to force the angular.element library. This should be used to force either jqLite by leaving ng-jq blank or setting the name of the jquery variable under window (eg. jQuery).
Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page - e.g. on the <body> or <html> tags.
The ngProp directive binds an expression to a DOM element property. ngProp allows writing to arbitrary properties by including the property name in the attribute, e.g. ng-prop-value="'my value'" binds 'my value' to the valueproperty.
The ngOn directive adds an event listener to a DOM element via angular.element().on(), and evaluates an expression when the event is fired. ngOn allows adding listeners for arbitrary events by including the event name in the attribute, e.g. ng-on-drop="onDrop()" executes the 'onDrop()' expression when the drop event is fired.
a
Modifies the default behavior of the html a tag so that the default action is prevented when the href attribute is empty.
Using AngularJS markup like {{hash}} in an href attribute will make the link go to the wrong URL if the user clicks it before AngularJS has a chance to replace the {{hash}} markup with its value. Until AngularJS replaces the markup the link will be broken and will most likely return a 404 error. The ngHref directive solves this problem.
Using AngularJS markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until AngularJS replaces the expression inside {{hash}}. The ngSrc directive solves this problem.
Using AngularJS markup like {{hash}} in a srcset attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until AngularJS replaces the expression inside {{hash}}. The ngSrcset directive solves this problem.
This directive sets the disabled attribute on the element (typically a form control, e.g. inputbuttonselect etc.) if the expression inside ngDisabled evaluates to truthy.
Sets the checked attribute on the element, if the expression inside ngChecked is truthy.
Sets the readonly attribute on the element, if the expression inside ngReadonly is truthy. Note that readonlyapplies only to input elements with specific types. See the input docs on MDN for more information.
Sets the selected attribute on the element, if the expression inside ngSelected is truthy.
Sets the open attribute on the element, if the expression inside ngOpen is truthy.
Helper directive that makes it possible to create control groups inside a form directive. These "child forms" can be used, for example, to determine the validity of a sub-group of controls.
Directive that instantiates FormController.
HTML textarea element control with AngularJS data-binding. The data-binding and validation properties of this element are exactly the same as those of the input element.
HTML input element control. When used together with ngModel, it provides data-binding, input state control, and validation. Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
Binds the given expression to the value of the element.
The ngBind attribute tells AngularJS to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.
The ngBindTemplate directive specifies that the element text content should be replaced with the interpolation of the template in the ngBindTemplate attribute. Unlike ngBind, the ngBindTemplate can contain multiple {{ }}expressions. This directive is needed since some HTML elements (such as TITLE and OPTION) cannot contain SPAN elements.
Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default, the resulting HTML content will be sanitized using the $sanitize service. To utilize this functionality, ensure that $sanitize is available, for example, by including ngSanitize in your module's dependencies (not in core AngularJS). In order to use ngSanitize in your module's dependencies, you need to include "angular-sanitize.js" in your application.
Evaluate the given expression when the user changes the input. The expression is evaluated immediately, unlike the JavaScript onchange event which only triggers at the end of a change (usually, when the user leaves the form element or presses the return key).
The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.
The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in conjunction with ngRepeat and take effect only on odd (even) rows.
The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in conjunction with ngRepeat and take effect only on odd (even) rows.
The ngCloak directive is used to prevent the AngularJS html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.
The ngController directive attaches a controller class to the view. This is a key aspect of how angular supports the principles behind the Model-View-Controller design pattern.
AngularJS has some features that can conflict with certain restrictions that are applied when using CSP (Content Security Policy) rules.
The ngClick directive allows you to specify custom behavior when an element is clicked.
The ngDblclick directive allows you to specify custom behavior on a dblclick event.
The ngMousedown directive allows you to specify custom behavior on mousedown event.
Specify custom behavior on mouseup event.
Specify custom behavior on mouseover event.
Specify custom behavior on mouseenter event.
Specify custom behavior on mouseleave event.
Specify custom behavior on mousemove event.
Specify custom behavior on keydown event.
Specify custom behavior on keyup event.
Specify custom behavior on keypress event.
Enables binding AngularJS expressions to onsubmit events.
Specify custom behavior on focus event.
Specify custom behavior on blur event.
Specify custom behavior on copy event.
Specify custom behavior on cut event.
Specify custom behavior on paste event.
The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
Fetches, compiles and includes an external HTML fragment.
The ngInit directive allows you to evaluate an expression in the current scope.
Text input that converts between a delimited string and an array of strings. The default delimiter is a comma followed by a space - equivalent to ng-list=", ". You can specify a custom delimiter as the value of the ngList attribute - for example, ng-list=" | ".
The ngModel directive binds an input,selecttextarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
This directive allows you to modify the behaviour of ngModel directives within your application. You can specify an ngModelOptions directive on any element. All ngModel directives will use the options of their nearest ngModelOptions ancestor.
The ngNonBindable directive tells AngularJS not to compile or bind the contents of the current DOM element, including directives on the element itself that have a lower priority than ngNonBindable. This is useful if the element contains what appears to be AngularJS directives and bindings but which should be ignored by AngularJS. This could be the case if you have a site that displays snippets of code, for instance.
The ngOptions attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object obtained by evaluating the ngOptions comprehension expression.
ngPluralize is a directive that displays messages according to en-US localization rules. These rules are bundled with angular.js, but can be overridden (see AngularJS i18n dev guide). You configure ngPluralize directive by specifying the mappings between plural categories and the strings to be displayed.
The ngRef attribute tells AngularJS to assign the controller of a component (or a directive) to the given property in the current scope. It is also possible to add the jqlite-wrapped DOM element to the scope.
The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.
The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShowattribute.
The ngHide directive shows or hides the given HTML element based on the expression provided to the ngHideattribute.
The ngStyle directive allows you to set CSS style on an HTML element conditionally.
The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression. Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location as specified in the template.
Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
Load the content of a <script> element into $templateCache, so that the template can be used by ngInclude,ngView, or directives. The type of the <script> element must be specified as text/ng-template, and a cache name for the template must be assigned through the element's id, which can then be used as a directive's templateUrl.
HTML select element with AngularJS data-binding.
ngRequired adds the required validator to ngModel. It is most often used for input and select controls, but can also be applied to custom controls.
ngPattern adds the pattern validator to ngModel. It is most often used for text-based input controls, but can also be applied to custom text-based controls.
ngMaxlength adds the maxlength validator to ngModel. It is most often used for text-based input controls, but can also be applied to custom text-based controls.
ngMinlength adds the minlength validator to ngModel. It is most often used for text-based input controls, but can also be applied to custom text-based controls.
Object
Name
Description
An object that contains information about the current AngularJS version.
Type
Name
Description
Interface for configuring AngularJS modules.
A cache object used to store and retrieve data, primarily used by $templateRequest and the scriptdirective to cache templates and other data.
A shared object between directive compile / linking functions which contains normalized DOM element attributes. The values reflect current binding state {{ }}. The normalization is needed since all of these are treated as equivalent in AngularJS:
FormController keeps track of all its controls and nested forms as well as the state of them, such as being valid/invalid or dirty/pristine.
NgModelController provides API for the ngModel directive. The controller contains services for data-binding, validation, CSS updates, and value formatting and parsing. It purposefully does not contain any logic which deals with DOM rendering or listening to DOM events. Such DOM related logic should be provided by other directives which make use of NgModelController for data-binding to control elements. AngularJS provides this DOM logic for most input elements. At the end of this page you can find a custom control example that uses ngModelController to bind to contenteditable elements.
A container for the options set by the ngModelOptions directive
The controller for the select directive. The controller exposes a few utility methods that can be used to augment the behavior of a regular or an ngOptions select element.
A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created automatically when compiled HTML template is executed.) See also the Scopes guide for an in-depth introduction and usage examples.
Provider
Name
Description
Use $anchorScrollProvider to disable automatic scrolling whenever $location.hash() changes.
Default implementation of $animate that doesn't perform any animations, instead just synchronously performs DOM updates and resolves the returned runner promise.
The $controller service is used by AngularJS to create new controllers.
Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function.
Use $httpProvider to change the default behavior of the $http service.
Used for configuring the interpolation markup. Defaults to {{ and }}.
Use the $locationProvider to configure how the application deep linking paths are stored.
Use the $logProvider to configure how the application logs messages
$parseProvider can be used for configuring the default behavior of the $parse service.
Provider for the $rootScope service.
The $sceDelegateProvider provider allows developers to configure the $sceDelegate service, used as a delegate for Strict Contextual Escaping (SCE).
The $sceProvider provider allows developers to configure the $sce service.
  • enable/disable Strict Contextual Escaping (SCE) in a module
  • override the default implementation with a custom delegate
Used to configure the options passed to the $http service when making a template request.
Service
Name
Description
When called, it scrolls to the element related to the specified hash or (if omitted) to the current value of $location.hash(), according to the rules specified in the HTML5 spec.
The $animate service exposes a series of DOM utility methods that provide support for animation hooks. The default behavior is the application of DOM operations, however, when an animation is detected (and animations are enabled), $animate will do the heavy lifting to ensure that animation runs with the triggered DOM operation.
This is the core version of $animateCss. By default, only when the ngAnimate is included, then the $animateCss service will actually perform animations.
Factory that constructs Cache objects and gives access to them.
$templateCache is a Cache object created by the $cacheFactory.
Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
$controller service is responsible for instantiating controllers.
jQuery or jqLite wrapper for the browser's window.document object.
Any uncaught exception in AngularJS expressions is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console.
Filters are used for formatting data displayed to the user.
Default $http params serializer that converts objects to strings according to the following rules:
Alternative $http params serializer that follows jQuery's param() method logic. The serializer will also sort the params alphabetically.
The $http service is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
Factory function used to create XMLHttpRequest objects.
HTTP backend used by the service that delegates to XMLHttpRequest object or JSONP and deals with browser incompatibilities.
Compiles a string with markup into an interpolation function. This service is used by the HTML $compileservice for data binding. See $interpolateProvider for configuring the interpolation markup.
AngularJS's wrapper for window.setInterval. The fn function is executed every delay milliseconds.
This service handles the lifecycle of callbacks to handle JSONP requests. Override this service if you wish to customise where the callbacks are stored and how they vary compared to the requested url.
$locale service provides localization rules for various AngularJS components. As of right now the only public api is:
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.
Simple service for logging. Default implementation safely writes the message into the browser's console (if present).
Converts AngularJS expression into a function.
A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.
The root element of AngularJS application. This is either the element where ngApp was declared or the element passed into angular.bootstrap. The element represents the root element of application. It is also the location where the application's $injector service gets published, and can be retrieved using $rootElement.injector().
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 event emission/broadcast and subscription facility. See the developer guide on scopes.
$sceDelegate is a service that is used by the $sce service to provide Strict Contextual Escaping (SCE)services to AngularJS.
$sce is a service that provides Strict Contextual Escaping services to AngularJS.
The $templateRequest service runs security checks then downloads the provided template using $httpand, upon success, stores the contents inside of $templateCache. If the HTTP request fails or the response data of the HTTP request is empty, a $compile error will be thrown (the exception can be thwarted by setting the 2nd parameter of the function to true). Note that the contents of $templateCacheare trusted, so the call to $sce.getTrustedUrl(tpl) is omitted when tpl is of type string and $templateCache has the matching entry.
AngularJS's wrapper for window.setTimeout. The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service.
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 AngularJS we always refer to it through the$window service, so it may be overridden, removed or mocked for testing.
Input
Name
Description
Standard HTML text input with AngularJS data binding, inherited by most of the input elements.
Input with date validation and transformation. In browsers that do not yet support the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 date format (yyyy-MM-dd), for example: 2009-01-06. Since many modern browsers do not yet support this input type, it is important to provide cues to users on the expected input format via a placeholder or label.
Input with datetime validation and transformation. In browsers that do not yet support the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 local datetime format (yyyy-MM-ddTHH:mm:ss), for example: 2010-12-28T14:57:00.
Input with time validation and transformation. In browsers that do not yet support the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 local time format (HH:mm:ss), for example: 14:57:00. Model must be a Date object. This binding will always output a Date object to the model of January 1, 1970, or local date new Date(1970, 0, 1, HH, mm, ss).
Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 week format (yyyy-W##), for example: 2013-W02.
Input with month validation and transformation. In browsers that do not yet support the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 month format (yyyy-MM), for example: 2009-01.
Text input with number validation and transformation. Sets the number validation error if not a valid number.
Text input with URL validation. Sets the url validation error key if the content is not a valid URL.
Text input with email validation. Sets the email validation error key if not a valid email address.
HTML radio button.
Native range input with validation and transformation.
HTML checkbox.
Filter
Name
Description
Selects a subset of items from array and returns it as a new array.
Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used.
Formats a number as text.
Formats date to a string based on the requested format.
Allows you to convert a JavaScript object into JSON string.
Converts string to lowercase.
Converts string to uppercase.
Creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit. Other array-like objects are also supported (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input, it is converted to a string.
Returns an array containing the items from the specified collection, ordered by a comparator function based on the values computed using the expression predicate.



broadcast() as well as $emit() allow you to raise an event in your AngularJS application. The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers.

An event raised by $broadcast() and $emit() can be handled by wiring an event handler using $on() method. A typical call to $on() will look like this:

$scope.$on("MyEvent", function(evt,data){ 
  // handler code here });





























































Comments

  1. This is most informative and also this post most user friendly and super navigation to all posts. Thank you so much
    Angular JS Online training
    Angular JS training in Hyderabad

    ReplyDelete

Post a Comment

Popular posts from this blog

Chat Bot

Entity Framework

Microsoft Enterprise Library-Data Access Application Block for for .Net Core & .Net Standard