This section is a work in progress. Its content will be updated regularly but
feel free to rely on AngularJS documentation
in the meantime.
What is AngularTS?
AngularTS is buildless, type-safe and reactive JS framework for building
stuctured web applications at any scale. It continues the legacy of
AngularJS by providing the best developer experience
via immediate productivity without the burden of JS ecosystem tooling. Getting
started with AngularTS does not even require JavaScript. All you need is a
little bit of HTML. Below is a canonical example of a counter:
This code demonstrates the following key AngularTS features:
HTML-first: AngularTS is designed for HTML-first approach, meaning your
application logic can be expressed declaratively in your markup using custom
attributes–called directives. Here, we are using ng-init directive to
initialize our application state and ng-click directive to add an event
handler that changes our state.
Template-driven: AngularTS’s built-in template engine automatically keeps
the UI in sync with your application state, eliminating the need for manual
DOM tracking and updates. The {{count}} expression above is an example of
Angular’s interpolation syntax. As the value of count variable increases,
our UI is updated with the new state.
Island-first and zero-cost: AngularTS creates an application on any HTML
tag with ng-app attribute, allowing multiple independent applications
(modules) to live on a single page. This allows AngularTS to work alongside
your existing tech stack where the majority of your page is rendered on the
server, while AngularTS is isolated to small “islands” (regions of your page)
where custom interactivity or personalization is required.
Micro-framework appearance: With its minimal setup, AngularTS is
well-suited for quick experiments, LLM-generated code, and learning web
development in general. But beneath its lightweight surface, it supports
structured enterprise design patterns, MVC architecture, and component-driven
design. With its rich directive library, state-based routing and support for
animations, AngularTS is a complete package for building large SPAs, server,
mobile, and desktop applications.
1 - Directives
1.1 -
1.2 - ng-app
Bootstrap AngularTS application
Description
Use this directive to auto-bootstrap an AngularTS application. The ng-app
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.
1.3 - ng-bind
Sync or hydrate textContent of element with an expression
Description
The ng-bind attribute places 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.
Typically, you don’t use ng-bind directly, but instead you use the double
curly markup like {{ expression }} which is similar but less verbose.
It is preferable to use ng-bind instead of {{ expression }} if a template is
momentarily displayed by the browser in its raw state before it is compiled.
Since ng-bind is an element attribute, it makes the bindings invisible to the
user while the page is loading.
An alternative solution to this problem would be using the ng-cloak directive.
ng-bind can be modified with a data-lazy data attribute (or shorthand lazy
attribute), which will delay update of element content until model is changed.
This is useful for rendering server-generated content, while keeping the UI
dynamic. In other frameworks, this technieque is known as
hydration.
Description: Expression to evaluate and modify
textContent
property.
Example:
<divng-bind="name"></div>
Directive modifiers
data-lazy
Type: N/A
Description: Apply expression once the bound model changes.
Example:
<divng-bind="name"data-lazy></div><!-- or --><divng-bind="name"lazy></div>
Demo
<sectionng-app><!-- Eager bind --><label>Enter name: <inputtype="text"ng-model="name"/></label><br/> Hello <spanng-bind="name">I am never displayed</span>!
<!-- Lazy bind with short-hand `lazy` --><buttonng-click="name1 = name">Sync</button><spanng-bind="name1"lazy>I am server content</span>!
</section>
Hello I am never displayed!
I am server content!
1.4 - ng-blur
Handler for blur event
Description
The ng-blur directive allows you to specify custom behavior when an element
loses focus.
Description: Expression to evaluate upon
blur
event.
FocusEvent
object is available as $event.
Example:
<divng-blur="$ctrl.handleBlur($event)"></div>
Demo
<sectionng-app><inputtype="text"ng-blur="count = count + 1"ng-init="count = 0"placeholder="Click or tab away from me"/> Lost focus {{ count }} times
</section>
Lost focus {{ count }} times
1.5 - ng-channel
Subscribe a template to a messaging service topic
Description
Updates element’s content by subscribing to events published on a named channel
using $eventBus.
If the element does not contain any child elements or templates, the
directive will replace the element’s inner HTML with the published value.
If the element does contain a template and the published value is an
object, the directive will merge the object’s key-value pairs into the
current scope, allowing Angular expressions like to be evaluated and
rendered.
The directive automatically unsubscribes from the event channel when the scope
is destroyed.
Parameters
ng-channel
Type:string
Description: The name of the channel to subscribe to using $eventBus.
Demo
<divng-app><!-- With empty node --><divng-channel="epoch"></div><!-- With template --><divng-channel="user">Hello {{ user.firstName }} {{ user.lastName }}</div></div><buttonclass="btn btn-dark"onclick='angular.$eventBus.publish("epoch", Date.now())'> Publish epoch
</button><buttonclass="btn btn-dark"onclick='angular.$eventBus.publish("user", {user: {
firstName: "John",
lastName: "Smith"
}})'> Publish name
</button>
Hello {{ user.firstName }} {{ user.lastName }}
1.6 - ng-class
Dynamically bind one or more CSS classes using expressions.
Description
The ng-class directive allows dynamically setting CSS classes on an HTML
element by binding to an expression. The directive supports the following
expression types:
String — space-delimited class names.
Object — keys as class names and values as booleans. Truthy values add the
class.
Array — containing strings and/or objects as described above.
When the expression changes:
Previously added classes are removed.
New classes are added.
Duplicate classes are avoided.
Important: Avoid using interpolation ({{ ... }}) in the value of the
class attribute together with ng-class. See
interpolation known issues for
details.
Animations
If data-animate attribute is present, the following animations will be applied
to the element:
Description: An expression evaluating to a space-delimited string or array
of class names.
Example:
<divng-repeat="item in items"ng-class-even="'even-row'"></div>
Demo
<sectionng-app><style>.even-row{background-color:gainsboro;}</style><divng-repeat="item in [1,2,3,4]"ng-class-even="'even-row'">{{item}}</div></section>
{{item}}
1.8 - ng-class-odd
Apply CSS classes to odd-indexed elements inside ng-repeat.
Description
The ng-class-odd directive works just like ng-class, but it
applies only to odd-indexed elements inside an ng-repeat
block.
Must be used inside ng-repeat.
Animations
If data-animate attribute is present, the following animations will be applied
to the element:
The ng-cloak directive is used to prevent the 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 directive can be applied to the <body> element, but the preferred usage is
to apply multiple ng-cloak directives to small portions of the page to permit
progressive rendering of the browser view.
ng-cloak works in cooperation with the following CSS rule:
The ng-el directive allows you to store a reference to a DOM element in the
current scope, making it accessible elsewhere in your template or from your
controller. The reference is automatically removed if the element is removed
from the DOM.
Parameters
ng-el
Type:string (optional)
Description: Name of the key under which the element will be stored in
scope. If omitted, the element’s id attribute will be used.
Example:
<divid="box"ng-el="$box"></div>
Demo
<sectionng-app><divng-el="$chesireCat"></div><divng-elid="response"></div><buttonclass="btn"ng-el="$button"ng-click="
$chesireCat.innerHTML = '🐱';
response.innerHTML='That depends a good deal on where you want to get to.';
$button.hidden = true"> Which way I ought to go?
</button></section>
1.15 - ng-focus
Handler for focus event
Description
The ng-focus directive allows you to specify custom behavior when an element
is focused.
Description: Expression to evaluate upon
focus
event.
FocusEvent
object is available as $event.
Example:
<divng-focus="$ctrl.greet($event)"></div>
Demo
<sectionng-app><inputtype="text"ng-focus="count = count + 1"ng-init="count = 0"placeholder="Click or tab into me"/> Focused {{ count }} times
</section>
Focused {{ count }} times
1.16 - ng-get
Initiates a GET request
Description
The ng-get directive allows you to fetch content via $http service from a
remote URL and insert, replace, or manipulate it into the DOM. For DOM
manipulation to work, the response must be HTML content. If the server endpoint
returns a JSON-response, the directive will treat it as an object to be merged
into the current scope and the swap strategy will be ignored.
Example
<section><divng-get="/json">Get</div><!-- Enpoint returns {name: 'Bob'}--> {{ name }}
<!-- 'Bob' will be merged into current scope. --></section>
In case of error, the directive displays the error in place of success result or
will merge it into the current scope if response contains JSON.
Example
<section><divng-post="/json">Get</div><!-- Enpoint returns 404 with {error: 'Not found'}--> {{ error }}
<!-- 'Not found' will be merged into current scope. Nothing to swap --></section>
Additional options for request and response handling can be modified with
attributes provided below.
Parameters
ng-get
Type:string
Description: A URL to issue a GET request to
Example:
<divng-get="/example">get</div>
Modifiers
data-trigger
Type:string
Description: Specifies the DOM event for triggering a request (default is
click). For a complete list, see
UI Events. To
eagerly execute a request without user interaction, use the “load” event,
which is triggered syntheticaly on any element by the directive linking
function. This is in contract to the native
load,
which executes lazily only for window object and certain resource elements.
Description: Triggers a request whenever its value changes. This attribute
can be used with interpolation (e.g., {{ expression }}) to observe reactive
changes in the scope.
Example:
<divng-get="/example"latch="{{ latch }}"ng-mouseover="latch = !latch"> Get
</div>
The ng-inject directive injects registered injectables (services, factories,
etc.) into the current scope for direct access within templates or expressions.
This allows access to application state without having to create intermediary
controllers.
When applied to an element, the directive reads a semicolon-separated list of
injectables’ names from the ng-inject attribute and attempts to retrieve them
from the $injector. Each resolved injectable is attached to the current scope
under its corresponding name.
Parameters
ng-inject
Type:string
Restrict:A
Description: A semicolon-separated list of injectable’ names to attach to current scope.
Description: Expression to evaluate upon
keydown
event.
KeyboardEvent
object is available as $event.
Example:
<divng-keydown="$ctrl.greet($event)"></div>
Demo
<sectionng-app><inputtype="text"ng-keydown="count = count + 1"ng-init="count = 0"placeholder="Click here, then press down a key."/> Keydown {{ count }} times
</section>
Keydown {{ count }} times
1.20 - ng-keyup
Handler for keyup event
Description
The ng-keyup directive allows you to specify custom behavior when releasing
keys, regardless of whether they produce a character value.
Description: Expression to evaluate upon
keyup
event.
KeyboardEvent
object is available as $event.
Example:
<divng-keyup="$ctrl.greet($event)"></div>
Demo
<sectionng-app><inputtype="text"ng-keyup="count = count + 1"ng-init="count = 0"placeholder="Click here, then press down a key."/> Keyup {{ count }} times
</section>
Keyup {{ count }} times
1.21 - ng-load
Handler for load event
Description
The ng-load directive allows you to specify custom behavior for elements that
trigger
load
event.
Note: there is no guarantee that the browser will bind ng-load directive
before loading its resource. Demo below is using a large image to showcase
itself.
Description: Expression to evaluate upon
mouseup
event.
MouseEvent
object is available as $event.
Example:
<divng-mouseup="$ctrl.greet($event)"></div>
Demo
<sectionng-app><divng-init="count = 0"ng-mouseup="count = count + 1">Mouse Up</div> Mouse Up {{ count }} times
</section>
Mouse Up
Mouse Up {{ count }} times
1.29 - ng-non-bindable
Stops compilation for element
Description
The ng-non-bindable directive tells the framework 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 directives and bindings but which should be ignored.
This could be the case if you have a site that displays snippets of code, for
instance.
ng-non-bindable
Type: N/A
Description: Stops compilation process for element
The ng-post directive allows you to send data via $http service to a remote
URL and insert, replace, or manipulate the server’s response into the DOM. The
directive assumes a response will be HTML content. If the server endpoint
returns a JSON-response, the directive will treat it as an object to be merged
into the current scope. In such a case, the swap strategy will be ignored and
the content will be interpolated into current scope. Unlike its sister ng-get
directive, ng-post assumes it is attached to a form, input, textarea, or
select element, which act as the source of data for request payload:
In case of error, the directive displays the error in place of success result or
will merge it into the current scope if response contains JSON. The behavior can
be combined with other directivs to create complex form-handling strategies.
Below is a form that dissappears in case of success or adds error state in case
of validation errors.
Additional options for request and response handling can be modified with
attributes provided below.
Parameters
ng-post
Type:string
Description: A URL to issue a GET request to
Example:
<divng-post="/example">post</div>
Modifiers
data-enctype
Type:string
Description: Specifies the content type of form. Defaults to
application/json. To send regular URL-encoded data form, use
application/x-www-form-urlencoded.
Description: Specifies the DOM event for triggering a request (default is
click). For a complete list, see
UI Events. To
eagerly execute a request without user interaction, use the “load” event,
which is triggered syntheticaly on any element by the directive linking
function. This is in contract to the native
load,
which executes lazily only for window object and certain resource elements.
Description: Triggers a request whenever its value changes. This attribute
can be used with interpolation (e.g., {{ expression }}) to observe reactive
changes in the scope.
Example:
<divng-post="/example"latch="{{ latch }}"ng-mouseover="latch = !latch"> Get
</div>
The ng-window-* directive allows you to specify custom behavior for events
dispatched from Window object. The event name is defined by including it in
the placeholder of directive’s name. Example: ng-window-online will bind the
directive to the online event. For a full list of standard options, see
events.
Instance of PubSubProvider for
configuring the $eventBus service. The default implementation returns the
global angular.EventBus instance, which is an async instance of
PubSub class.
If the ngSanitize module is included, $sceDelegate will use $sanitize to
clean untrusted HTML automatically.
AngularTS’ default $sceDelegate allows loading from your app’s domain,
blocking others unless explicitly whitelisted.
This small overhead provides major security benefits and simplifies auditing.
Supported Trusted Contexts
Context
Description
$sce.HTML
Safe HTML (used by ng-bind-html).
$sce.CSS
Safe CSS. Currently unused.
$sce.MEDIA_URL
Safe media URLs (auto-sanitized).
$sce.URL
Safe navigable URLs.
$sce.RESOURCE_URL
Safe resource URLs (used in ng-include, iframe, etc.).
$sce.JS
Safe JavaScript for execution.
⚠️ Before AngularTS 1.7.0, a[href] and img[src] sanitized directly. As of 1.7.0, these now use $sce.URL and $sce.MEDIA_URL respectively.
Resource URL List Patterns
Trusted and banned resource URL lists accept:
'self' → matches same domain & protocol
Strings with wildcards:
* → matches within a single path segment
** → matches across path segments (use carefully)
Regular expressions (RegExp)
Caution: Regex patterns are powerful but harder to maintain — use only
when necessary.
Disabling SCE (Not Recommended)
You can disable SCE globally — though this is strongly discouraged.
angular.module('myAppWithSceDisabled',[]).config(function($sceProvider){// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects or libraries.
$sceProvider.enabled(false);});
2.5 - $templateCacheProvider
Cache provider for $templateCache service.
Description
Initializes cache instance for $templateCache service as an empty
Map
object.
An alternative caching implementation can be provided by implementing
TemplateCache interface for web
standard storage options like localStorage, sessionStorage, IndexedDB, or
Cache API. You can also use third-party storage engines like
pouch or
SQLite. With WebAssembly (WASM),
even more powerful and flexible storage backends become possible.
Below is an example implementation using localStorage:
A messaging service, backed by an instance of
PubSub. This implementation is based on
the original
Google Closure PubSub
but uses
Promise.resolve()
instead of
Window.setTimeout()
for its async implementation. $eventBus allows communication between an
Angular application instance and the outside context, which can be a different
module, a non-Angular application, a third-party party library, or even a WASM
application. Additionally, $eventBus can be used to communicate directly with
a template, using ng-channel directive.
$eventBus should not be used for communicating between Angular’s own
primitives.
For sharing application state: use custom Services and Factories that
encapsulate your business logic and manage your model.
For intercomponent communication: use $scope.$on(), $scope.$emit(),
and $scope.$broadcast() methods.
The example below demonstrates communication between the global window context
and a controller. Note: Ensure topic clean-up after the $scope is
destroyed
Example
<sectionng-app="demo"><divng-controller="DemoCtrl as $ctrl"> Milliseconds elapsed since the epoch <b>{{ $ctrl.ms }}</b></div></section><!--We are using a regular onclick and `angular` global --><buttonclass="btn btn-dark"onclick="angular.$eventBus.publish('demo', Date.now())"> Publish time
</button>
window.angular.module('demo',[]).controller('DemoCtrl',class{static$inject=['$eventBus','$scope'];constructor($eventBus,$scope){constkey=$eventBus.subscribe('demo',(val)=>{// `this.ms = val` will not work because `this` is not a proxy
// to trigger change detection, we access controller as a scope property
$scope.$ctrl.ms=val;});$scope.$on('$destroy',()=>$eventBus.unsubscribeByKey(key));}},);
Demo
Milliseconds elapsed since the epoch {{ $ctrl.ms }}
The $http service is a core AngularTS service that facilitates communication
with remote HTTP servers via the browser’s
XMLHttpRequest object or via
JSONP.
For unit testing applications that use the $http service, see
$httpBackend mock.
For a higher-level abstraction, see the
$resource
service.
The $http API is based on the
$q deferred/promise APIs.
Familiarity with these APIs is important for advanced usage.
General Usage
The $http service is a function that takes a single argument — a
configuration object — used to generate an HTTP request. It returns a
promise that resolves on success or rejects on failure with a response
object.
$http({method:'GET',url:'/someUrl'}).then(functionsuccessCallback(response){// Called asynchronously when the response is available
},functionerrorCallback(response){// Called asynchronously if an error occurs or the server returns an error
});ShortcutMethodsShortcutmethodsareavailableforallcommonHTTPmethods.AllrequireaURL;POST/PUTrequestsrequiredata.Anoptionalconfigobjectcanbepassedasthelastargument.$http.get('/someUrl',config).then(successCallback,errorCallback);$http.post('/someUrl',data,config).then(successCallback,errorCallback);Shortcutmethodslist:$http.get$http.head$http.post$http.put$http.delete$http.patch$http.get(...);SettingHTTPHeadersThe$httpserviceautomaticallyaddscertainHTTPheaderstoallrequests.Thesedefaultscanbeconfiguredusing$httpProvider.defaults.headers.Defaultheaders:Commonheaders:Accept:application/json,text/plain,*/*POSTheaders:Content-Type:application/jsonPUTheaders:Content-Type:application/jsonYoucanmodifydefaults:$httpProvider.defaults.headers.get={'My-Header':'value'};Ormodifyheadersgloballyatruntime:module.run(function($http){$http.defaults.headers.common.Authorization='Basic YmVlcDpib29w';});Per-requestoverrides:letreq={method:'POST',url:'http://example.com',headers:{'Content-Type':undefined},data:{test:'test'}};$http(req).then(success,error);TransformingRequestsandResponsesRequestsandresponsescanbetransformedusingtransformRequestandtransformResponse.Eachcanbeasinglefunctionoranarrayoffunctions.Functionstake(data,headersGetter[,status])andreturnthetransformedvalue.Note:AngularTSdoesnotmakeacopyofdatabeforepassingittotransformRequest.Avoidsideeffects.Defaulttransformations:Requests:objectsareserializedtoJSONResponses:XSRFprefixremoved;JSONresponsesareparsedPer-requestoverrideexample:functionappendTransform(defaults,transform){defaults=angular.isArray(defaults)?defaults:[defaults];returndefaults.concat(transform);}$http({url:'...',method:'GET',transformResponse:appendTransform($http.defaults.transformResponse,function(value){returndoTransform(value);})});CachingBydefault,$httpresponsesarenotcached.Enablecachingwith:config.cache=trueoracacheobjectGlobaldefaultcache:$http.defaults.cache=trueOnlyGETandJSONPrequestsarecached.InterceptorsInterceptorsallowmodificationofrequests/responsesglobally.Addfactoriesto$httpProvider.interceptors.Interceptortypes:request(config)requestError(rejection)response(response)responseError(rejection)Example:$provide.factory('myHttpInterceptor',function($q){return{request:function(config){returnconfig;},responseError:function(rejection){return$q.reject(rejection);}};});$httpProvider.interceptors.push('myHttpInterceptor');
3.5 - $interpolate
HTTP service
3.6 - $location
URL normalization for HTML5/hashbang modes
Description
The $location service parses the URL in the browser address bar (based on the
window.location) and makes
the URL available to your application in a uniform manner. Changes to the URL in
the address bar are reflected into $location service and changes to
$location are reflected into the browser address bar. Using $location you
can:
Watch and observe the URL
Change the URL
Detect users changes to address bar by clicking on links or using back or
forward buttons in browser
To configure the HTML5 mode and link behavior for the service, use the
$locationProvider.
Events
$location#$locationChangeStart
Description: Broadcast on root scope before a URL will change. This change
can be prevented by calling preventDefault method of the event. See
Scope#$ons for more details about event object. Upon successful change
$location#$locationChangeSuccess is fired.
The newState and oldState parameters may be defined only in HTML5 mode and
when the browser supports the HTML5 History API.
Parameters: | angularEvent | Object | No | Synthetic event object. | |
newUrl | string | No | The new URL being navigated to. | | oldUrl |
string | Yes | The URL prior to the change. | | newState | string | Yes
| New history state object (HTML5 mode only). | | oldState | string | Yes
| Previ
$location#$locationChangeSuccess
Description: Broadcasted on the root scope after a URL was changed. The newState and
oldState parameters may be defined only in HTML5 mode and when the browser
supports the HTML5 History API.
Parameters
| angularEvent | Object | No | Synthetic event object. | | newUrl |
string | No | The new URL after change. | | oldUrl | string | Yes | The
previous URL before the change. | | newState | string | Yes | New history
state object (HTML5 mode only). | | oldState | string | Yes | Previous
history state object (HTML5 mode only). |
3.7 - $log
Logging service
Using $log
Default implementation of
LogService safely writes the
message into the browser’s
console (if
present). The main purpose of this service is to simplify debugging and
troubleshooting, while allowing the developer to modify the defaults for live
environments.
Note: Not all browsers support blackboxing. The default is to log debug messages. You can use
$logProvider.debug
to change this.
For configuration and custom implementations, see
$logProvider.
Decorating $log
You can also optionally override any of the $log service methods with
$provide decorator. Below is a simple example that overrides default
$log.error to log errors to both console and a backend endpoint.
If your application is already heavily reliant on default
console logging or
you are using a third-party library where logging cannot be overriden, you can
still take advantage of Angular’s services by modifying the globals at runtime.
Below is an example that overrides default console.error to logs errors to
both console and a backend endpoint.
Example*
angular.module('demo').run(($http)=>{/**
* Decorate console.error to log error messages to the server.
*/const$delegate=window.console.error;window.console.error=(...args)=>{try{consterrorMessage=args.map((arg)=>(arginstanceofError?arg.stack:JSON.stringify(arg))).join(' ');$delegate.apply(console,args);$http.post('/api/log/error',{message:errorMessage});}catch(e){console.warn(e);}};/**
* Detect errors thrown outside Angular and report them to the server.
*/window.addEventListener('error',(e)=>{window.console.error(e.error||e.message,e);});/**
* Optionally: Capture unhandled promise rejections
*/window.addEventListener('unhandledrejection',(e)=>{window.console.error(e.reason||e);});});
Combining both $log decoration and console.log overriding provides a robust
and flexible error reporting strategy that can adapt to your use-case.
* array notation and HTTP error handling omitted for brevity
3.8 - $parse
URL normalization for HTML5/hashbang modes
3.9 - $rootElement
URL normalization for HTML5/hashbang modes
3.10 - $rootScope
Root scope service
3.11 - $sce
Strict Contextual Escaping service
$sceProvider and $sce Documentation
$sceProvider
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
If the ngSanitize module is included, $sceDelegate will use $sanitize to
clean untrusted HTML automatically.
AngularTS’ default $sceDelegate allows loading from your app’s domain,
blocking others unless explicitly whitelisted.
This small overhead provides major security benefits and simplifies auditing.
Supported Trusted Contexts
Context
Description
$sce.HTML
Safe HTML (used by ng-bind-html).
$sce.CSS
Safe CSS. Currently unused.
$sce.MEDIA_URL
Safe media URLs (auto-sanitized).
$sce.URL
Safe navigable URLs.
$sce.RESOURCE_URL
Safe resource URLs (used in ng-include, iframe, etc.).
$sce.JS
Safe JavaScript for execution.
⚠️ Before AngularTS 1.7.0, a[href] and img[src] sanitized directly. As of 1.7.0, these now use $sce.URL and $sce.MEDIA_URL respectively.
Resource URL List Patterns
Trusted and banned resource URL lists accept:
'self' → matches same domain & protocol
Strings with wildcards:
* → matches within a single path segment
** → matches across path segments (use carefully)
Regular expressions (RegExp)
Caution: Regex patterns are powerful but harder to maintain — use only
when necessary.
Disabling SCE (Not Recommended)
You can disable SCE globally — though this is strongly discouraged.
angular.module('myAppWithSceDisabled',[]).config(function($sceProvider){// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects or libraries.
$sceProvider.enabled(false);});
3.12 - $templateCache
Map object for storing templates
$templateCache is a
Map
object created by $templateCacheProvider.
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 by
using $templateRequest or by consuming the $templateCache service directly.
Note: the script tag containing the template does not need to be included in the
head of the document, but it must be a descendent of the $rootElement (e.g.
element with ng-app attribute), otherwise the template will be ignored.
Adding via the $templateCache service:
Example
constmyApp=angular.module('myApp',[]).run(($templateCache)=>{$templateCache.set('templateId.html','This is the content of the template');});
To retrieve the template, simply use it in your component:
Selects a subset of items from array and returns it as a new array.
@param {Array} array The source array.
Note: If the array contains objects that reference themselves, filtering
is not possible.
@param {string|Object|function()} expression The predicate to be used for
selecting items from
array.
Can be one of:
string: The string is used for matching against the contents of the
array. All strings or
objects with string properties in `array` that match this string will be returned. This also
applies to nested object properties.
The predicate can be negated by prefixing the string with `!`.
Object: A pattern object can be used to filter specific properties on
objects contained
by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
which have property `name` containing "M" and property `phone` containing "1". A special
property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
against any property of the object or its nested object properties. That's equivalent to the
simple substring match with a `string` as described above. The special property name can be
overwritten, using the `anyPropertyKey` parameter.
The predicate can be negated by prefixing the string with `!`.
For example `{name: "!M"}` predicate will return an array of items which have property `name`
not containing "M".
Note that a named property will match properties on the same level only, while the special
`$` property will match properties on the same level or deeper. E.g. an array item like
`{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
**will** be matched by `{$: 'John'}`.
function(value, index, array): A predicate function can be used to write
arbitrary filters.
The function is called for each element of the array, with the element, its index, and
the entire array itself as arguments.
The final result is an array of those elements that the predicate returned true for.
@param {function(actual, expected)|true|false} [comparator] Comparator which
is used in
determining if values retrieved using `expression` (when it is not a function) should be
considered a match based on the expected value (from the filter expression) and actual
value (from the object in the array).
Can be one of:
function(actual, expected):
The function will be given the object value and the predicate value to compare and
should return true if both values should be considered equal.
true: A shorthand for
function(actual, expected) { return angular.equals(actual, expected)}.
This is essentially strict comparison of expected and actual.
false: A short hand for a function which will look for a substring match
in a case
insensitive way. Primitive values are converted to strings. Objects are not compared against
primitives, unless they have a custom `toString` method (e.g. `Date` objects).
Defaults to false.
@param {string} [anyPropertyKey] The special property name that matches
against any property.
By default `$`.
*/
4.2 -
JSON Filter
Description
Allows you to convert a JavaScript object into a JSON string.
This filter is mostly useful for debugging. When using the double curly
{{value}} notation, the binding is automatically converted to JSON.
Parameters
object{*}: Any JavaScript object (including arrays and primitive types)
to filter.
spacing{number=}: The number of spaces to use per indentation, defaults
to 2.
Returns
{string}: JSON string.
4.3 -
limitTo Filter
Description
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.
Parameters
input{Array|ArrayLike|string|number}: Array/array-like, string, or
number to be limited.
limit{string|number}: The length of the returned array or string.
If the limit number is positive, limit number of items from the
beginning of the source array/string are copied.
If the number is negative, limit number of items from the end of the
source array/string are copied.
The limit will be trimmed if it exceeds array.length.
If limit is undefined, the input will be returned unchanged.
begin{(string|number)=}: Index at which to begin limitation. As a
negative index, begin indicates an offset from the end of input. Defaults
to 0.
Returns
{Array|string}: A new sub-array or substring of length limit or less if
the input had less than limit elements.
4.4 -
OrderBy Filter
Description
Returns an array containing the items from the specified collection, ordered
by a comparator function based on the values computed using the expression
predicate.
For example, [{id: 'foo'}, {id: 'bar'}] | orderBy:'id' would result in
[{id: 'bar'}, {id: 'foo'}].
The collection can be an Array or array-like object (e.g., NodeList, jQuery
object, TypedArray, String, etc).
The expression can be a single predicate or a list of predicates, each serving
as a tie-breaker for the preceding one. The expression is evaluated against
each item and the output is used for comparing with other items.
You can change the sorting order by setting reverse to true. By default,
items are sorted in ascending order.
The comparison is done using the comparator function. If none is specified, a
default, built-in comparator is used (see below for details - in a nutshell, it
compares numbers numerically and strings alphabetically).
Under the Hood
Ordering the specified collection happens in two phases:
All items are passed through the predicate (or predicates), and the returned
values are saved along with their type (string, number, etc). For
example, an item {label: 'foo'}, passed through a predicate that extracts
the value of the label property, would be transformed to:
{value:'foo',type:'string',index:...}
Note: null values use ’null’ as their type. 2. The comparator function is used
to sort the items, based on the derived values, types, and indices.
If you use a custom comparator, it will be called with pairs of objects of the
form {value: …, type: ‘…’, index: …} and is expected to return 0 if the
objects are equal (as far as the comparator is concerned), -1 if the 1st one
should be ranked higher than the second, or 1 otherwise.
To ensure that the sorting will be deterministic across platforms, if none of
the specified predicates can distinguish between two items, orderBy will
automatically introduce a dummy predicate that returns the item’s index as
value. (If you are using a custom comparator, make sure it can handle this
predicate as well.)
If a custom comparator still can’t distinguish between two items, then they will
be sorted based on their index using the built-in comparator.
Finally, in an attempt to simplify things, if a predicate returns an object as
the extracted value for an item, orderBy will try to convert that object to a
primitive value before passing it to the comparator. The following rules govern
the conversion:
If the object has a valueOf() method that returns a primitive, its return value
will be used instead. (If the object has a valueOf() method that returns another
object, then the returned object will be used in subsequent steps.) If the
object has a custom toString() method (i.e., not the one inherited from Object)
that returns a primitive, its return value will be used instead. (If the object
has a toString() method that returns another object, then the returned object
will be used in subsequent steps.) No conversion; the object itself is used. The
Default Comparator The default, built-in comparator should be sufficient for
most use cases. In short, it compares numbers numerically, strings
alphabetically (and case-insensitively), for objects falls back to using their
index in the original collection, sorts values of different types by type, and
puts undefined and null values at the end of the sorted list.
More specifically, it follows these steps to determine the relative order of
items:
If the compared values are of different types: If one of the values is
undefined, consider it “greater than” the other. Else if one of the values is
null, consider it “greater than” the other. Else compare the types themselves
alphabetically. If both values are of type string, compare them alphabetically
in a case- and locale-insensitive way. If both values are objects, compare their
indices instead. Otherwise, return: 0, if the values are equal (by strict
equality comparison, i.e., using ===). -1, if the 1st value is “less than” the
2nd value (compared using the < operator). 1, otherwise. Note: If you notice
numbers not being sorted as expected, make sure they are actually being saved as
numbers and not strings. Note: For the purpose of sorting, null and undefined
are considered “greater than” any other value (with undefined “greater than”
null). This effectively means that null and undefined values end up at the end
of a list sorted in ascending order. Note: null values use ’null’ as their type
to be able to distinguish them from objects.
Parameters collection {Array|ArrayLike}: The collection (array or array-like
object) to sort.
expression {(Function|string|Array.<Function|string>)=}: A predicate (or list of
predicates) to be used by the comparator to determine the order of elements.
Can be one of:
Function: A getter function. This function will be called with each item as an
argument and the return value will be used for sorting. string: An AngularTS
expression. This expression will be evaluated against each item and the result
will be used for sorting. For example, use ’label’ to sort by a property called
label or ’label.substring(0, 3)’ to sort by the first 3 characters of the label
property. (The result of a constant expression is interpreted as a property name
to be used for comparison. For example, use ‘“special name”’ (note the extra
pair of quotes) to sort by a property called special name.) An expression can be
optionally prefixed with + or - to control the sorting direction, ascending or
descending. For example, ‘+label’ or ‘-label’. If no property is provided,
(e.g., ‘+’ or ‘-’), the collection element itself is used in comparisons. Array:
An array of function and/or string predicates. If a predicate cannot determine
the relative order of two items, the next predicate is used as a tie-breaker.
Note: If the predicate is missing or empty, then it defaults to ‘+’.
reverse {boolean=}: If true, reverse the sorting order.
comparator {(Function)=}: The comparator function used to determine the relative
order of value pairs. If omitted, the built-in comparator will be used.
Returns {Array}: The sorted array.
5 - Values
5.1 - $document
Injectable window.document object
Description
An injectable wrapper for window.documentobject . Useful for
mocking a browser dependency in non-browser environment tests:
Example:
// value injectables are overriden
angular.module('demo',[]).value('$document',{});
When combined with ng-inject directive, the wrapper also makes document
object directly accessible in the template scope.