This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Documentation

Welcome to AngularTS documentation.

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:

Example

<section ng-app ng-cloak>
  <button class="btn btn-dark" ng-init="count = 0" ng-click="count = count + 1">
    Count is: {{ count }}
  </button>
</section>

Result


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.

Parameters


ng-bind

  • Type: Expression

  • Restrict: A

  • Element: ANY

  • Priority: 0

  • Description: Expression to evaluate and modify textContent property.

  • Example:

    <div ng-bind="name"></div>
    

Directive modifiers

data-lazy

  • Type: N/A

  • Description: Apply expression once the bound model changes.

  • Example:

    <div ng-bind="name" data-lazy></div>
    <!-- or -->
    <div ng-bind="name" lazy></div>
    

Demo

<section ng-app>
  <!-- Eager bind -->
  <label>Enter name: <input type="text" ng-model="name" /></label><br />
  Hello <span ng-bind="name">I am never displayed</span>!

  <!-- Lazy bind with short-hand `lazy` -->
  <button ng-click="name1 = name">Sync</button>
  <span ng-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.

Parameters


ng-blur

  • Type: Expression

  • Description: Expression to evaluate upon blur event. FocusEvent object is available as $event.

  • Example:

    <div ng-blur="$ctrl.handleBlur($event)"></div>
    

Demo

<section ng-app>
  <input
    type="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

<div ng-app>
  <!-- With empty node -->
  <div ng-channel="epoch"></div>

  <!-- With template -->
  <div ng-channel="user">Hello {{ user.firstName }} {{ user.lastName }}</div>
</div>

<button
  class="btn btn-dark"
  onclick='angular.$eventBus.publish("epoch", Date.now())'
>
  Publish epoch
</button>

<button
  class="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:

AnimationOccurs
add-classBefore the class is applied to the element
remove-classBefore the class is removed from the element
set-classBefore classes are simultaneously added and removed

ng-class supports standard CSS3 transitions/animations even if they don’t follow $animate service naming conventions.

Parameters


ng-class

  • Type: string | object | array

  • Description: An expression whose result determines the CSS classes to apply.

  • Example:

    <div ng-class="{ active: isActive, disabled: isDisabled }"></div>
    

Demo

<style>
  .strike {
    text-decoration: line-through;
  }
  .bold {
    font-weight: bold !important;
  }
  .red {
    color: red;
  }
  .has-error {
    color: red;
    background-color: yellow;
  }
  .orange {
    color: orange;
  }
</style>
<section ng-app>
  <p ng-class="{strike: deleted, bold: important, 'has-error': error}">
    Map Syntax Example
  </p>
  <label>
    <input type="checkbox" ng-model="deleted" />deleted (apply "strike" class)
  </label>
  <br />
  <label>
    <input type="checkbox" ng-model="important" />important (apply "bold" class)
  </label>
  <br />
  <label>
    <input type="checkbox" ng-model="error" />error (apply "has-error" class)
  </label>
  <hr />
  <p ng-class="style">Using String Syntax</p>
  <input
    type="text"
    ng-model="style"
    placeholder="Type: bold strike red"
    aria-label="Type: bold strike red"
  />
  <hr />
  <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  <input
    ng-model="style1"
    placeholder="Type: bold, strike or red"
    aria-label="Type: bold, strike or red"
  /><br />
  <input
    ng-model="style2"
    placeholder="Type: bold, strike or red"
    aria-label="Type: bold, strike or red 2"
  /><br />
  <input
    ng-model="style3"
    placeholder="Type: bold, strike or red"
    aria-label="Type: bold, strike or red 3"
  /><br />
  <hr />
  <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  <input
    ng-model="style4"
    placeholder="Type: bold, strike"
    aria-label="Type: bold, strike"
  />
  <br />
  <label
    ><input type="checkbox" ng-model="warning" /> warning (apply "orange"
    class)</label
  >
</section>

Map Syntax Example




Using String Syntax


Using Array Syntax





Using Array and Map Syntax



1.7 - ng-class-even

Apply CSS classes to even-indexed elements inside ng-repeat.

Description

The ng-class-even directive works just like ng-class, but it applies only to even-indexed elements in 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:

AnimationOccurs
add-classBefore the class is applied to the element
remove-classBefore the class is removed from the element

Parameters


ng-class-even

  • Type: string | array

  • Description: An expression evaluating to a space-delimited string or array of class names.

  • Example:

    <div ng-repeat="item in items" ng-class-even="'even-row'"></div>
    

Demo

<section ng-app>
  <style>
    .even-row {
      background-color: gainsboro;
    }
  </style>
  <div ng-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:

AnimationOccurs
add-classBefore the class is applied to the element
remove-classBefore the class is removed from the element

Parameters


ng-class-odd

  • Type: string | array

  • Description: An expression evaluating to a space-delimited string or array of class names.

  • Example:

    <div ng-repeat="item in items" ng-class-odd="'odd-row'"></div>
    

Demo

<section ng-app>
  <style>
    .odd-row {
      background-color: gainsboro;
    }
  </style>
  <div ng-repeat="item in [1,2,3,4]" ng-class-odd="'odd-row'">{{item}}</div>
</section>
{{item}}

1.9 - ng-click

Handler for click event

Description

The ng-click directive allows you to specify custom behavior when an element is clicked.

Parameters


ng-click

  • Type: Expression

  • Restrict: A

  • Element: ANY

  • Priority: 0

  • Description: Expression to evaluate upon click event. PointerEvent object is available as $event.

  • Example:

    <div ng-click="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <button class="btn btn-dark" ng-init="count = 0" ng-click="count = count + 1">
    Increment
  </button>
  <span> count: {{count}} </span>
</section>
count: {{count}}

1.10 - ng-cloak

Hide interpolated templates

Description

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:

@charset "UTF-8";

[ng-cloak],
[data-ng-cloak],
.ng-cloak,
.ng-hide:not(.ng-hide-animate) {
  display: none !important;
}

.ng-animate-shim {
  visibility: hidden;
}

.ng-anchor {
  position: absolute;
}

CSS styles are available in npm distribution:

<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/@angular-wave/angular.ts/css/angular.min.css"
/>

Example

<style>
  @charset "UTF-8";
  .ng-cloak,
  .ng-hide:not(.ng-hide-animate),
  [data-ng-cloak],
  [ng-cloak] {
    display: none !important;
  }
  .ng-animate-shim {
    visibility: hidden;
  }
  .ng-anchor {
    position: absolute;
  }
</style>
<section ng-app ng-cloak>These tags are invisible {{ hello }}</section>

Demo

These tags are invisible {{ hello }}

1.11 - ng-copy

Handler for copy event

Description

The ng-copy directive allows you to specify custom behavior when an element is copied.

Parameters


ng-copy

  • Type: Expression

  • Description: Expression to evaluate upon copy event. ClipboardEvent object is available as $event.

  • Example:

    <div contenteditable="true" ng-copy="$ctrl.greet($event)">Content</div>
    

Demo

<section ng-app>
  <div class="border p-2" ng-copy="copied = true" contenteditable="true">
    Copy text from this box via Ctrl-C
  </div>
  {{ copied }}
</section>
Copy text from this box via Ctrl-C
{{ copied }}

1.12 - ng-cut

Handler for cut event

Description

The ng-cut directive allows you to specify custom behavior when an element is cut.

Parameters


ng-cut

  • Type: Expression

  • Description: Expression to evaluate upon cut event. ClipboardEvent object is available as $event.

  • Example:

    <div contenteditable="true" ng-cut="$ctrl.onCut($event)">
      Cuttable content
    </div>
    

Demo

<section ng-app>
  <div class="border p-2" ng-cut="cut = true" contenteditable="true">
    Cut text from this box via Ctrl-X
  </div>
  {{ cut }}
</section>
Cut text from this box via Ctrl-X
{{ cut }}


1.13 - ng-dblclick

Handler for dblclick event

Description

The ng-dblclick directive allows you to specify custom behavior when an element is double clicked.

Parameters


ng-dblclick

  • Type: Expression

  • Restrict: A

  • Element: ANY

  • Priority: 0

  • Description: Expression to evaluate upon dblclick event. MouseEvent object is available as $event.

  • Example:

    <div ng-dblclick="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <button
    class="btn btn-dark"
    ng-init="count = 0"
    ng-dblclick="count = count + 1"
  >
    Increment
  </button>
  <span> count: {{count}} </span>
</section>
count: {{count}}

1.14 - ng-el

Reference to an element

Description

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:

    <div id="box" ng-el="$box"></div>
    

Demo

<section ng-app>
  <div ng-el="$chesireCat"></div>
  <div ng-el id="response"></div>
  <button
    class="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.

Parameters


ng-focus

  • Type: Expression

  • Description: Expression to evaluate upon focus event. FocusEvent object is available as $event.

  • Example:

    <div ng-focus="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <input
    type="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>
  <div ng-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>
  <div ng-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:

    <div ng-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.

  • Example:

    <div ng-get="/example" trigger="mouseover">Get</div>
    

data-latch

  • Type: string

  • 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:

    <div ng-get="/example" latch="{{ latch }}" ng-mouseover="latch = !latch">
      Get
    </div>
    

data-swap

  • Type: SwapMode

  • Description: Controls how the response is inserted

  • Example:

    <div ng-get="/example" swap="outerHTML">Get</div>
    

data-target

  • Type: selectors

  • Description: Specifies a DOM element where the response should be rendered or name of scope property for response binding

  • Example:

    <div ng-get="/example" target=".test">Get</div>
    <div ng-get="/json" target="person">{{ person.name }}</div>
    

data-delay

  • Type: delay

  • Description: Delay request by N millisecond

  • Example:

    <div ng-get="/example" delay="1000">Get</div>
    

data-interval

  • Type: delay

  • Description: Repeat request every N milliseconds

  • Example:

    <div ng-get="/example" interval="1000">Get</div>
    

data-throttle

  • Type: delay

  • Description: Ignores subsequent requests for N milliseconds

  • Example:

    <div ng-get="/example" throttle="1000">Get</div>
    

data-loading

  • Type: N/A

  • Description: Adds a data-loading=“true/false” flag during request lifecycle.

  • Example:

    <div ng-get="/example" data-loading>Get</div>
    

data-loading-class

  • Type: string

  • Description: Toggles the specified class on the element while loading.

  • Example:

    <div ng-get="/example" data-loading-class="red">Get</div>
    

data-success

  • Type: Expression

  • Description: Evaluates expression when request succeeds. Response data is available as a $res property on the scope.

  • Example:

    <div ng-get="/example" success="message = $res">Get {{ message }}</div>
    

data-error

  • Type: Expression

  • Description: Evaluates expression when request fails. Response data is available as a $res property on the scope.

  • Example:

    <div ng-get="/example" error="errormessage = $res">
      Get {{ errormessage }}
    </div>
    

data-success-state

  • Type: string

  • Description: Name of the state to nagitate to when request succeeds

  • Example:

    <ng-view></ng-view>
    <div ng-get="/example" success-state="account">Get</div>
    

data-success-error

  • Type: string

  • Description: Name of the state to nagitate to when request fails

  • Example:

    <ng-view></ng-view>
    <div ng-get="/example" error-state="login">Get</div>
    

1.17 - ng-include

Include a template

Description

1.18 - ng-inject

Inject dependencies into scope.

Description

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.

  • Example:

    <div ng-inject="userService;accountService"></div>
    

Demo

<section ng-app>
  <div ng-inject="$window"></div>
  {{ $window.document.location }}
</section>
{{ $window.document.location }}

1.19 - ng-keydown

Handler for keydown event

Description

The ng-keydown directive allows you to specify custom behavior when pressing keys, regardless of whether they produce a character value.

Parameters


ng-keydown

  • Type: Expression

  • Description: Expression to evaluate upon keydown event. KeyboardEvent object is available as $event.

  • Example:

    <div ng-keydown="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <input
    type="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.

Parameters


ng-keyup

  • Type: Expression

  • Description: Expression to evaluate upon keyup event. KeyboardEvent object is available as $event.

  • Example:

    <div ng-keyup="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <input
    type="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.

Parameters


ng-load

  • Type: Expression

  • Description: Expression to evaluate upon load event. Event object is available as $event.

  • Example:

    <img src="url" ng-load="$ctrl.load($event)"></div>
    

Demo

<section ng-app>
  <img
    ng-load="res = 'Large image loaded'"
    width="150px"
    src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Centroamerica_prehispanica_siglo_XVI.svg/1920px-Centroamerica_prehispanica_siglo_XVI.svg.png"
  />
  {{ res }}
</section>
{{ res }}

1.22 - ng-mousedown

Handler for mousedown event

Description

The ng-mousedown directive allows you to specify custom behavior when a mouse is pressed over an element.

Parameters


ng-mousedown

  • Type: Expression

  • Description: Expression to evaluate upon mousedown event. MouseEvent object is available as $event.

  • Example:

    <div ng-mousedown="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <button ng-init="count = 0" ng-mousedown="count = count + 1">
    Press Mouse Down
  </button>
  Mouse Down {{ count }} times
</section>
Mouse Down {{ count }} times

1.23 - ng-mouseenter

Handler for mouseenter event

Description

The ng-mouseenter directive allows you to specify custom behavior when a mouse enters an element.

Parameters


ng-mouseenter

  • Type: Expression

  • Description: Expression to evaluate upon mouseenter event. MouseEvent object is available as $event.

  • Example:

    <div ng-mouseenter="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <div ng-init="count = 0" ng-mouseenter="count = count + 1">Mouse Enter</div>
  Mouse Enter {{ count }} times
</section>
Mouse Enter
Mouse Enter {{ count }} times

1.24 - ng-mouseleave

Handler for mouseleave event

Description

The ng-mouseleave directive allows you to specify custom behavior when an element a mouse leaves entire element.

Parameters


ng-mouseleave

  • Type: Expression

  • Description: Expression to evaluate upon mouseleave event. MouseEvent object is available as $event.

  • Example:

    <div ng-mouseleave="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <div ng-init="count = 0" ng-mouseleave="count = count + 1">Mouse Leave</div>
  Mouse Leave {{ count }} times
</section>
Mouse Leave
Mouse Leave {{ count }} times

1.25 - ng-mousemove

Handler for mousemove event

Description

The ng-mousemove directive allows you to specify custom custom behavior when a mouse is moved over an element.

Parameters


ng-mousemove

  • Type: Expression

  • Description: Expression to evaluate upon mousemove event. MouseEvent object is available as $event.

  • Example:

    <div ng-mousemove="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <div ng-init="count = 0" ng-mousemove="count = count + 1">Mouse Move</div>
  Mouse Move {{ count }} times
</section>
Mouse Move
Mouse Move {{ count }} times

1.26 - ng-mouseout

Handler for mouseout event

Description

The ng-mouseout directive allows you to specify custom behavior when a mouse leaves any part of the element or its children.

Parameters


ng-mouseout

  • Type: Expression

  • Description: Expression to evaluate upon mouseout event. MouseEvent object is available as $event.

  • Example:

    <div ng-mouseout="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <div ng-init="count = 0" ng-mouseout="count = count + 1">Mouse Out</div>
  Mouse Out {{ count }} times
</section>
Mouse Out
Mouse Out {{ count }} times

1.27 - ng-mouseover

Handler for mouseover event

Description

The ng-mouseover directive allows you to specify custom behavior when a mouse is placed over an element.

Parameters


ng-mouseover

  • Type: Expression

  • Description: Expression to evaluate upon mouseover event. MouseEvent object is available as $event.

  • Example:

    <div ng-mouseover="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <div ng-init="count = 0" ng-mouseover="count = count + 1">Mouse Over</div>
  Mouse Over {{ count }} times
</section>
Mouse Over
Mouse Over {{ count }} times

1.28 - ng-mouseup

Handler for mouseup event

Description

The ng-mouseup directive allows you to specify custom behavior when a pressed mouse is released over an element.

Parameters


ng-mouseup

  • Type: Expression

  • Description: Expression to evaluate upon mouseup event. MouseEvent object is available as $event.

  • Example:

    <div ng-mouseup="$ctrl.greet($event)"></div>
    

Demo

<section ng-app>
  <div ng-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

  • Priority: 1000

  • Element: ANY

  • Example:

    <section ng-app>
        <div ng-non-bindable>{{ 2 + 2 }}</div>
      </section>
      

    {{ 2 + 2 }}

1.30 - ng-post

Initiates a POST request

Description

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:

Example

<form ng-post="/register">
  <input name="username" type="text" />
</form>

With form elements, the directive can be registered anywhere inside a form:

Example

<form>
  <input name="username" type="text" />
  <button ng-post="/register">Send</button>
</form>

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.

Example

<form
  ng-post="/register"
  ng-if="$ctrl.success === false"
  success="$ctrl.success = true"
>
  <h2>Register form</h2>

  <label ng-class="{ error: errors.username }">
    Username
    <input
      name="username"
      type="text"
      aria-invalid="{{ errors.username !== undefined}}"
      ng-keyup="errors.username = undefined"
    />
    <span>{{ errors.username }}</span>
  </label>

  <button type="submit">Sign up</button>
</form>

For other input elements, the directive adds form-like behavior. The example below showcases an input acting as a search form:

<input
  name="seach"
  ng-post="/search"
  target="#output"
  trigger="keyup"
  placeholder="Search..."
/>

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:

    <div ng-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.

  • Example:

    <form ng-post="/urlencoded" enctype="application/x-www-form-urlencoded">
      <input type="text" name="name" />
    </form>
    

data-form

  • Type: string

  • Description: If placed outside a form element, specifies id of the form to use for datasource.

  • Example:

    <button ng-post="/register" form="register">Send</button>
    <form id="register">
      <input name="username" type="text" />
    </form>
    

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.

  • Example:

    <div ng-post="/example" trigger="mouseover">Get</div>
    

data-latch

  • Type: string

  • 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:

    <div ng-post="/example" latch="{{ latch }}" ng-mouseover="latch = !latch">
      Get
    </div>
    

data-swap

  • Type: SwapMode

  • Description: Controls how the response is inserted

  • Example:

    <div ng-post="/example" swap="outerHTML">Get</div>
    

data-target

  • Type: selectors

  • Description: Specifies a DOM element where the response should be rendered or name of scope property for response binding

  • Example:

    <div ng-post="/example" target=".test">Post</div>
    <div ng-post="/json" target="person">{{ person.name }}</div>
    

data-delay

  • Type: delay

  • Description: Delay request by N millisecond

  • Example:

    <div ng-post="/example" delay="1000">Get</div>
    

data-interval

  • Type: delay

  • Description: Repeat request every N milliseconds

  • Example:

    <div ng-post="/example" interval="1000">Get</div>
    

data-throttle

  • Type: delay

  • Description: Ignores subsequent requests for N milliseconds

  • Example:

    <div ng-post="/example" throttle="1000">Get</div>
    

data-loading

  • Type: N/A

  • Description: Adds a data-loading=“true/false” flag during request lifecycle.

  • Example:

    <div ng-post="/example" data-loading>Get</div>
    

data-loading-class

  • Type: string

  • Description: Toggles the specified class on the element while loading.

  • Example:

    <div ng-post="/example" data-loading-class="red">Get</div>
    

data-success

  • Type: Expression

  • Description: Evaluates expression when request succeeds. Response data is available as a $res property on the scope.

  • Example:

    <div ng-post="/example" success="message = $res">Get {{ message }}</div>
    

data-error

  • Type: Expression

  • Description: Evaluates expression when request fails. Response data is available as a $res property on the scope.

  • Example:

    <div ng-post="/example" error="errormessage = $res">
      Get {{ errormessage }}
    </div>
    

data-success-state

  • Type: string

  • Description: Name of the state to nagitate to when request succeeds

  • Example:

    <ng-view></ng-view>
    <div ng-post="/example" success-state="account">Get</div>
    

data-success-error

  • Type: string

  • Description: Name of the state to nagitate to when request fails

  • Example:

    <ng-view></ng-view>
    <div ng-post="/example" error-state="login">Get</div>
    

1.31 - ng-window-*

Handler for window events

Description

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.

Parameters


ng-window-*

  • Type: Expression

  • Description: Expression to evaluate upon event dispatch. Event object is available as $event.

  • Example:

    <div ng-window-message="data = $event.message.date">{{ data }}</div>
    

Demo

<section ng-app>
  Try disabling your network connection
  <div ng-window-online="online = true">Connected: {{ online }}</div>
  <div ng-window-offline="offline = true">Disconnected: {{ offline }}</div>
</section>
Try disabling your network connection
Connected: {{ online }}
Disconnected: {{ offline }}

2 - Providers

2.1 - $eventBusProvider

Configuration provider for $eventBus service.

Description

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.

Properties


$eventBusProvider.eventBus

Customize event bus instance.

  • Type: PubSub

  • Default: angular.EventBus

  • Example:

    angular.module('demo', []).config(($eventBusProvider) => {
      eventBusProvider.eventBus = new MyCustomPubsub();
    });
    

For service description, see $eventBus.

2.2 - $locationProvider

Configuration provider for $location service.

Description

Use the $locationProvider to configure how the application deep linking paths are stored.

Properties


$locationProvider.html5ModeConf

  • Type: Html5Mode

  • Default: { enabled: true, requireBase: false, rewriteLinks: true }

  • Example:

    angular.module('demo', []).config(($locationProvider) => {
      $locationProvider.html5ModeConf.enabled = false;
    });
    

2.3 - $logProvider

Configuration provider for $log service.

Description

Instance of LogProvider for configuring how the application logs messages.

Properties


$logProvider.debug

Enable or disable debug-level logging. Also see debug property.

  • Type: boolean

  • Default: false

  • Example:

    angular.module('demo', []).config(($logProvider) => {
      $logProvider.debug = true;
    });
    

Methods


$logProvider.setLogger()

Override the default logger with a custom implementation of the LogService interface.

  • Parameter: LogServiceFactory

  • Example:

    angular.module('demo', []).config(($logProvider) => {
      $logProvider.setLogger(() => ({
        log: () => {},
        info: () => {},
        warn: () => {},
        error: () => {},
        debug: () => {},
      }));
    });
    

For service description, see $log.

2.4 - $sceProvider

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

Read more about Strict Contextual Escaping (SCE).


$sce

$sce is a service that provides Strict Contextual Escaping (SCE) services to AngularTS.


Strict Contextual Escaping

Overview

Strict Contextual Escaping (SCE) is a mode in which AngularTS constrains bindings to only render trusted values. Its goal is to:

  • Help you write secure-by-default code.
  • Simplify auditing for vulnerabilities such as XSS and clickjacking.

By default, AngularTS treats all values as untrusted in HTML or sensitive URL bindings. When binding untrusted values, AngularTS will:

  • Sanitize or validate them based on context.
  • Or throw an error if it cannot guarantee safety.

Example — ng-bind-html renders its value directly as HTML (its “context”). If the input is untrusted, AngularTS will sanitize or reject it.

To bypass sanitization, you must mark a value as trusted before binding it.

Note: Since version 1.2, AngularTS ships with SCE enabled by default.


Example: Binding in a Privileged Context

<input ng-model="userHtml" aria-label="User input" />
<div ng-bind-html="userHtml"></div>

If SCE is disabled, this allows arbitrary HTML injection — a serious XSS risk.

To safely render user content, you should sanitize the HTML (on the server or client) before binding it.

SCE ensures that only trusted, validated, or sanitized values are rendered.

You can mark trusted values explicitly using:

$sce.trustAs(context, value);

or shorthand methods such as:

$sce.trustAsHtml(value);
$sce.trustAsUrl(value);
$sce.trustAsResourceUrl(value);

How It Works

Directives and Angular internals bind trusted values using:

$sce.getTrusted(context, value);

Example: the ngBindHtml directive uses $sce.parseAsHtml internally:

let ngBindHtmlDirective = [
  '$sce',
  function ($sce) {
    return function (scope, element, attr) {
      scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function (value) {
        element.html(value || '');
      });
    };
  },
];

Impact on Loading Templates

SCE affects both:

  • The ng-include directive
  • The templateUrl property in directives

By default, AngularTS loads templates only from the same domain and protocol as the main document.
It uses:

$sce.getTrustedResourceUrl(url);

To allow templates from other domains, use:

  • $sceDelegateProvider.trustedResourceUrlList
  • Or $sce.trustAsResourceUrl(url)

Note: Browser CORS and Same-Origin policies still apply.


Is This Too Much Overhead?

SCE applies only to interpolation expressions.

Constant literals are automatically trusted, e.g.:

<div ng-bind-html="'<b>implicitly trusted</b>'"></div>

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

ContextDescription
$sce.HTMLSafe HTML (used by ng-bind-html).
$sce.CSSSafe CSS. Currently unused.
$sce.MEDIA_URLSafe media URLs (auto-sanitized).
$sce.URLSafe navigable URLs.
$sce.RESOURCE_URLSafe resource URLs (used in ng-include, iframe, etc.).
$sce.JSSafe 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.


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:

class LocalStorageMap {
  constructor(prefix = '') {
    this.prefix = prefix;
  }

  _key(key) {
    return `${this.prefix}${key}`;
  }

  get(key) {
    const raw = localStorage.getItem(this._key(key));
    if (raw === null) return undefined;
    try {
      return JSON.parse(raw);
    } catch {
      return raw;
    }
  }

  set(key, value) {
    localStorage.setItem(this._key(key), value);
    return this;
  }

  has(key) {
    return localStorage.getItem(this._key(key)) !== null;
  }

  delete(key) {
    localStorage.removeItem(this._key(key));
    return true;
  }

  clear() {
    const toRemove = [];
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      if (k && k.startsWith(this.prefix)) {
        toRemove.push(k);
      }
    }
    toRemove.forEach((k) => localStorage.removeItem(k));
  }
}

Override during configuration phase:

angular.module('demo', []).config(($templateCacheProvider) => {
  templateCacheProvider.cache = new LocalStorageMap();
});

Properties


$templateCacheProvider.cache

Customize cache instance.

  • Type: TemplateCache

  • Default: Map

  • Example:

    angular.module('demo', []).config(($templateCacheProvider) => {
      templateCacheProvider.cache.set('test.html', 'hello');
    });
    

For service description, see $templateCache.

2.6 - $templateRequestProvider

Template request service

3 - Services

3.1 - $compile

Template compilation service

3.2 - $controller

Controller service

3.3 - $eventBus

Pubsub messaging service

Description

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

<section ng-app="demo">
  <div ng-controller="DemoCtrl as $ctrl">
    Milliseconds elapsed since the epoch <b>{{ $ctrl.ms }}</b>
  </div>
</section>

<!--We are using a regular onclick and `angular` global -->
<button
  class="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) {
      const key = $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 }}

For detailed method description, see PubSub


3.4 - $http

HTTP service

$http Service (AngularTS)

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(function successCallback(response) {
  // Called asynchronously when the response is available
}, function errorCallback(response) {
  // Called asynchronously if an error occurs or the server returns an error
});

Shortcut Methods

Shortcut methods are available for all common HTTP methods. All require a URL; POST/PUT requests require data. An optional config object can be passed as the last argument.

$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);


Shortcut methods list:

$http.get
$http.head
$http.post
$http.put
$http.delete
$http.patch

$http.get(...);

Setting HTTP Headers

The $http service automatically adds certain HTTP headers to all requests. These defaults can be configured using $httpProvider.defaults.headers.

Default headers:

Common headers: Accept: application/json, text/plain, */*

POST headers: Content-Type: application/json

PUT headers: Content-Type: application/json

You can modify defaults:

$httpProvider.defaults.headers.get = { 'My-Header': 'value' };


Or modify headers globally at runtime:

module.run(function($http) {
  $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
});


Per-request overrides:

let req = {
  method: 'POST',
  url: 'http://example.com',
  headers: {
    'Content-Type': undefined
  },
  data: { test: 'test' }
};

$http(req).then(success, error);

Transforming Requests and Responses

Requests and responses can be transformed using transformRequest and transformResponse. Each can be a single function or an array of functions. Functions take (data, headersGetter[, status]) and return the transformed value.

Note: AngularTS does not make a copy of data before passing it to transformRequest. Avoid side effects.

Default transformations:

Requests: objects are serialized to JSON

Responses: XSRF prefix removed; JSON responses are parsed

Per-request override example:

function appendTransform(defaults, transform) {
  defaults = angular.isArray(defaults) ? defaults : [defaults];
  return defaults.concat(transform);
}

$http({
  url: '...',
  method: 'GET',
  transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
    return doTransform(value);
  })
});

Caching

By default, $http responses are not cached. Enable caching with:

config.cache = true or a cache object

Global default cache: $http.defaults.cache = true

Only GET and JSONP requests are cached.

Interceptors

Interceptors allow modification of requests/responses globally. Add factories to $httpProvider.interceptors.

Interceptor types:

request(config)

requestError(rejection)

response(response)

responseError(rejection)

Example:

$provide.factory('myHttpInterceptor', function($q) {
  return {
    request: function(config) { return config; },
    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.

Example*
angular.module('demo').controller('MyController', ($log) => {
  $log.log('log');
  $log.info('info');
  $log.warn('warn!');
  $log.error('error');
  $log.debug('debug');
});

To reveal the location of the calls to $log in the JavaScript console, you can “blackbox” the AngularTS source in your browser:

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.

Example*
angular.module('demo').config(($provide) => {
  $provide.decorator('$log', ($delegate, $http, $exceptionHandler) => {
    const originalError = $delegate.error;
    $delegate.error = () => {
      originalError.apply($delegate, arguments);
      const errorMessage = Array.prototype.slice.call(arguments).join(' ');
      $http.post('/api/log/error', { message: errorMessage });
    };
    return $delegate;
  });
});

Overriding console

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 {
      const errorMessage = args
        .map((arg) => (arg instanceof Error ? 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

Read more about Strict Contextual Escaping (SCE).


$sce

$sce is a service that provides Strict Contextual Escaping (SCE) services to AngularTS.


Strict Contextual Escaping

Overview

Strict Contextual Escaping (SCE) is a mode in which AngularTS constrains bindings to only render trusted values. Its goal is to:

  • Help you write secure-by-default code.
  • Simplify auditing for vulnerabilities such as XSS and clickjacking.

By default, AngularTS treats all values as untrusted in HTML or sensitive URL bindings. When binding untrusted values, AngularTS will:

  • Sanitize or validate them based on context.
  • Or throw an error if it cannot guarantee safety.

Example — ng-bind-html renders its value directly as HTML (its “context”). If the input is untrusted, AngularTS will sanitize or reject it.

To bypass sanitization, you must mark a value as trusted before binding it.

Note: Since version 1.2, AngularTS ships with SCE enabled by default.


Example: Binding in a Privileged Context

<input ng-model="userHtml" aria-label="User input" />
<div ng-bind-html="userHtml"></div>

If SCE is disabled, this allows arbitrary HTML injection — a serious XSS risk.

To safely render user content, you should sanitize the HTML (on the server or client) before binding it.

SCE ensures that only trusted, validated, or sanitized values are rendered.

You can mark trusted values explicitly using:

$sce.trustAs(context, value);

or shorthand methods such as:

$sce.trustAsHtml(value);
$sce.trustAsUrl(value);
$sce.trustAsResourceUrl(value);

How It Works

Directives and Angular internals bind trusted values using:

$sce.getTrusted(context, value);

Example: the ngBindHtml directive uses $sce.parseAsHtml internally:

let ngBindHtmlDirective = [
  '$sce',
  function ($sce) {
    return function (scope, element, attr) {
      scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function (value) {
        element.html(value || '');
      });
    };
  },
];

Impact on Loading Templates

SCE affects both:

  • The ng-include directive
  • The templateUrl property in directives

By default, AngularTS loads templates only from the same domain and protocol as the main document.
It uses:

$sce.getTrustedResourceUrl(url);

To allow templates from other domains, use:

  • $sceDelegateProvider.trustedResourceUrlList
  • Or $sce.trustAsResourceUrl(url)

Note: Browser CORS and Same-Origin policies still apply.


Is This Too Much Overhead?

SCE applies only to interpolation expressions.

Constant literals are automatically trusted, e.g.:

<div ng-bind-html="'<b>implicitly trusted</b>'"></div>

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

ContextDescription
$sce.HTMLSafe HTML (used by ng-bind-html).
$sce.CSSSafe CSS. Currently unused.
$sce.MEDIA_URLSafe media URLs (auto-sanitized).
$sce.URLSafe navigable URLs.
$sce.RESOURCE_URLSafe resource URLs (used in ng-include, iframe, etc.).
$sce.JSSafe 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.


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.

Adding via the script tag:

Example

<script type="text/ng-template" id="templateId.html">
  <p>This is the content of the template</p>
</script>

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

const myApp = 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:

myApp.component('myComponent', {
  templateUrl: 'templateId.html',
});

or include it with ng-include:

<div ng-include="'templateId.html`"></div>

or get it via the $templateCache service:

myApp.controller(
  'Test',
  class {
    constructor($templateCache) {
      const tmp = $templateCache.get('templateId.html');
    }
  },
);

3.13 - $templateRequest

Template request service

3.14 - $url

URL management for state transitions

4 - Filters

4.1 -

/**

  • @ngdoc filter
  • @name filter
  • @kind function
  • @description
  • 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 `$`.
    
  • */