Little-known directives of Angular.js

Adam Stankiewicz

Little-known directives of Angular.js

During my recreational reading of Angular.js documentation I made a handful of notes describing some little-known, yet useful directives. Bon appétit.


Use it instead of form. Nest them at will, including validation.

<div ng-form name="userForm">
  <div ng-form name="contactForm"></div>

input types

Angular performs validation of HTML5 input types out of the box.

<input type="url">
<input type="email">
<input type="number" min="1" max="10">


The equivalent of putting {{ expression }} in an ng-cloak element, which additionally prevents your app from the Flash of Uncompiled Content.

Plus, it makes HTML in your templates (in our case Slim templates) look better.

<span ng-bind="">
<!-- equivalent of -->
<span ng-cloak>{{ }}</span>


Also prevents FUC, but contains multiple {{ expressions }}.

<span ng-bind-template="{{ }} {{ user.surname }}" />
<!-- equivalent of -->
<span ng-cloak>{{ }} {{ user.surname }}</span>

ng-bind-html & ng-bind-html-unsafe

Another variation of the above. Prevents FUC, and on top of that allows JavaScript execution and rendering of the result in safe or unsafe manner.

<!-- safe -->
<div ng-bind-html="renderHtml()">

<!-- possible script injection -->
<div ng-bind-html-unsafe="renderHtml()">


Enforces Content Security Policy support.

When using this directive, Angular never optimizes code by evaluating it using Function(string). Keep in mind that this may decrease the performance of your app.

You’ll find it indispensable when developing Google Chrome extensions.

<html ng-app ng-csp>
  <!-- no eval please -->


Converts comma-separated values in a view to an array in a model, and vice‑versa.

<!-- enter items as csv like "foo, bar" -->
<input ng-list ng-model="elements">

<!-- render both items in a list -->
<ul ng-repeat="element in elements">
  <li ng-bind="element">


Conditionally renders HTML. Handy if you want to avoid multiple ng-show elements.

<div ng-switch="search.type">
  <div ng-switch-when="zipcode"><!-- pick me --></div>
  <div ng-switch-when="geocode"><!-- or pick me! --></div>


Not strictly Angular.js feature, but soon-to-be. It’s the part of AngularUI Router and serves as an awesome alternative to ng-view. <!-- NOTE: -->

It supports — among others — states instead of routes (like in state machine), and prevents you from hard-coding links in your HTML by exposing ui-sref.


One of the coolest ui-router features which — according to the documentation:

binds a link (<a> tag) to a state. If the state has an associated URL, the directive will automatically generate & update the href attribute via the $state.href() method.

Adam Stankiewicz avatar
Adam Stankiewicz