Monday, 3 August 2015

AngularJS API



ng (core module)
The ng module is loaded by default when an AngularJS application is started. The module itself contains the essential components for an AngularJS application to function. The table below lists a high level breakdown of each of the services/factories, filters, directives and testing components available within this core module.

Module Components
Function
Name
Description
Converts the specified string to lowercase.
Example:
console.log(angular.lowercase("Dinesh"));
Converts the specified string to uppercase.
Example:
console.log(angular.uppercase("Dinesh"));
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.
Example:
var values = {
    name: 'misko',
    gender: 'male'
};
angular.forEach(values, function(value, key) {
    console.log(key + ': ' + value);
});
angular.forEach(values, function(i) {
    console.log(i);
});
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).
It creates a shallow copy of one or more sources provided and assign them to destination.
Example:

var mySource1 = {'name' : 'neha', 'age' : '26', obj2 : {}}
var mySource2 = {'course' : 'MCS'}
var myDest = {}
angular.extend(myDest, mySource1,mySource2)
console.log(myDest);
Output: {name: "neha", age: "26", course: "MCS", obj2: Object}
Now we check mySource1.obj2 === myDest.obj2, this will give true because both point to same reference of object. This is called as shallow copying.
NOTE:  angular.copy() is slower than angular.extend()
Deeply 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.merge({}, object1, object2).
Example:
var object1 = {
    "color": "yellow",
    "size" : null,
    "age" : 7,
    "weight" : null
}
var object2 = {
    "color": "blue",
    "size" : 51,
    "age" : null
}
var mergedObject = angular.merge(object1, object2);
console.log(mergedObject)
Output:
age: null
color: "blue"
size: 51
weight: null
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);
}
Example: 
function foo (callback) {
    // Do a lot of complex things

    callback();
}

// Those two have the same effect, but the later is more elegant
foo(function() {});
foo(angular.noop);
angular.noop is an empty function that can be used as a placeholder when you need to pass some function as a param.
A function that returns its first argument. This function is useful when writing code in the functional style.
Example:
function transformer(transformationFn, value) {
  return (transformationFn || angular.identity)(value);
};
In case transformationFn is provided as first parameter, it will be called with value as it's own parameter. Otherwise angular.identity function will be called with the same value.
Determines if a reference is undefined.
Example:
var variable;
console.log(angular.isUndefined(variable));
variable = 3; 
console.log(angular.isUndefined(variable));
Output:
True
False
Determines if a reference is defined.
Example:
var variable;
console.log(angular.isDefined(variable));
variable = 3; 
console.log(angular.isDefined(variable));
Output:
False
True
Determines if a reference is an Object. Unlike typeof in JavaScript, nulls are not considered to be objects. Note that JavaScript arrays are objects.
Example:
var variable;
console.log(angular.isObject(variable));
variable = []; 
console.log(angular.isObject(variable));
Output:
False
True
Determines if a reference is a String.
Example:
var variable;
console.log(angular.isString(variable));
variable = []; 
console.log(angular.isString(variable));
variable = ""; 
console.log(angular.isString(variable));
Output:
False
False
True
Determines if a reference is a Number.
Example:
var variable = [];
console.log(angular.isNumber(variable));
variable = "3"; 
console.log(angular.isNumber(variable));
variable = 4; 
console.log(angular.isNumber(variable));
Output:
False
False
True
Determines if a value is a date.
Example:
It checks whether the supplied value is a JavaScript Date object.
var cur_date = new Date(); 
var dt = "12/12/2015";   
console.log(angular.isDate(cur_date));   
console.log(angular.isDate(dt));  
Output:
True
False
Determines if a reference is an Array.
Example:
var sourceAry = [1,2,3,4,5,6]; 
var str = "www.techstrikers.com";
console.log(angular.isArray(sourceAry));   
console.log(angular.isArray(str));  
Output:
True
False
Determines if a reference is a Function.
Example:
Determines if a reference is a DOM element (or wrapped jQuery element).
Example:
Creates a deep copy of source, which should be an object or an array.
It creates a deep copy of source object or array and assign it to destination where ‘destination’ is optional. By writing deep copy, we mean that a new copy of the referred object is made.
Example:

var mySource = {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}
var myDest = {}
angular.copy(mySource, myDest);
console.log(myDest);
Output: {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}
If we check mySource.obj === myDest.obj, this will give false because both point to different objects. This is called as deep copying.
NOTE: angular.copy() is slower than angular.extend()
Determines if two objects or two values are equivalent. Supports value types, regular expressions, arrays and objects.
Example:
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.
Example:
Serializes input into a JSON-formatted string. Properties with leading $$ characters will be stripped since angular uses this notation internally.
Example:
Deserializes a JSON string.
Example:
Use this function to manually start up angular application.
Example:
Use this function to reload the current application with debug information turned on. This takes precedence over a call to $compileProvider.debugInfoEnabled(false).
Example:
Creates an injector object that can be used for retrieving services as well as for dependency injection (see dependency injection).
Example:
Wraps a raw DOM element or HTML string as a jQuery element.
Example:
The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism.
Example:
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.
a
Modifies the default behavior of the html A tag so that the default action is prevented when the href attribute is empty.
Using Angular markup like {{hash}} in an href attribute will make the link go to the wrong URL if the user clicks it before Angular has a chance to replace the {{hash}} markup with its value. Until Angular replaces the markup the link will be broken and will most likely return a 404 error. The ngHref directive solves this problem.
Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.
Using Angular markup like {{hash}} in a srcset attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrcset directive solves this problem.
This directive sets the disabled attribute on the element if the expression inside ngDisabled evaluates to truthy.
Sets the checked attribute on the element, if the expression inside ngChecked is truthy.
The HTML specification does not require browsers to preserve the values of boolean attributes such as readonly. (Their presence means true and their absence means false.) If we put an Angular interpolation expression into such an attribute then the binding information would be lost when the browser removes the attribute. The ngReadonly directive solves this problem for the readonly attribute. This complementary directive is not removed by the browser and so provides a permanent reliable place to store the binding information.
The HTML specification does not require browsers to preserve the values of boolean attributes such as selected. (Their presence means true and their absence means false.) If we put an Angular interpolation expression into such an attribute then the binding information would be lost when the browser removes the attribute. The ngSelected directive solves this problem for the selected attribute. This complementary directive is not removed by the browser and so provides a permanent reliable place to store the binding information.
The HTML specification does not require browsers to preserve the values of boolean attributes such as open. (Their presence means true and their absence means false.) If we put an Angular interpolation expression into such an attribute then the binding information would be lost when the browser removes the attribute. The ngOpen directive solves this problem for the open attribute. This complementary directive is not removed by the browser and so provides a permanent reliable place to store the binding information.
Nestable alias of form directive. HTML does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a sub-group of controls needs to be determined.
Directive that instantiates FormController.
HTML textarea element control with angular 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 <option> or input[radio], so that when the element is selected, the ngModel of that element is set to the bound value.
The ngBind attribute tells Angular 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 Angular). 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 Angular 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.
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 angular 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,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
Allows tuning how model updates are done. Using ngModelOptions you can specify a custom list of events that will trigger a model update and/or a debouncing delay so that the actual update only takes place when a timer expires; this timer will be reset after another change takes place.
The ngNonBindable directive tells Angular not to compile or bind the contents of the current DOM element. This is useful if the element contains what appears to be Angular directives and bindings but which should be ignored by Angular. 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 Angular i18n dev guide). You configure ngPluralize directive by specifying the mappings between plural categories and the strings to be displayed.
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 ngShow attribute. The element is shown or hidden by removing or adding the .ng-hide CSS class onto the element. The .ng-hide CSS class is predefined in AngularJS and sets the display style to none (using an !important flag). For CSP mode please add angular-csp.css to your html file (see ngCsp).
The ngHide directive shows or hides the given HTML element based on the expression provided to the ngHide attribute. The element is shown or hidden by removing or adding the ng-hide CSS class onto the element. The .ng-hide CSS class is predefined in AngularJS and sets the display style to none (using an !important flag). For CSP mode please add angular-csp.css to your html file (see ngCsp).
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 angular data-binding.
Object
Name
Description
An object that contains information about the current AngularJS version. This object has the following properties:
Type
Name
Description
Interface for configuring angular modules.
A cache object used to store and retrieve data, primarily used by $http and the script directive 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 Angular:
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. Angular 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.
The controller for the <select> directive. This provides support for reading and writing the selected value(s) of the control and also coordinates dynamically added <option> elements, perhaps by an ngRepeat directive.
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.)
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 Angular 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. This allows one to get/set the whitelists and blacklists used to ensure that the URLs used for sourcing Angular templates are safe. Refer $sceDelegateProvider.resourceUrlWhitelist and $sceDelegateProvider.resourceUrlBlacklist
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
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.
Factory that constructs Cache objects and gives access to them.
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.
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.
A jQuery or jqLite wrapper for the browser's window.document object.
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.
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 Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
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 $compile service for data binding. See $interpolateProvider for configuring the interpolation markup.
Angular's wrapper for window.setInterval. The fn function is executed every delay milliseconds.
$locale service provides localization rules for various Angular 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 Angular 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 Angular 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 an 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 $http and, 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 $templateCache are trusted, so the call to $sce.getTrustedUrl(tpl) is omitted when tpl is of type string and $templateCache has the matching entry.
Angular'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 angular 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 angular 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 date 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.
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. If a number is used as input, it is converted to a string.
Orders a specified array by the expression predicate. It is ordered alphabetically for strings and numerically for numbers. Note: if you notice numbers are not being sorted as expected, make sure they are actually being saved as numbers and not strings.