During my recreational reading of Angular.js documentation I made a handful of notes describing some little-known, yet useful directives. Bon appétit.
ng-form
Use it instead of form
. Nest them at will, including validation.
<div ng-form name="userForm">
<div ng-form name="contactForm"></div>
</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">
ng-bind
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="user.email">
<!-- equivalent of -->
<span ng-cloak>{{ user.email }}</span>
ng-bind-template
Also prevents FUC, but contains multiple {{ expressions }}
.
<span ng-bind-template="{{ user.name }} {{ user.surname }}" />
<!-- equivalent of -->
<span ng-cloak>{{ user.name }} {{ 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()">
ng-csp
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 -->
</html>
input[ng-list]
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">
</ul>
ng-switch
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>
</div>
ui-view
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: english.stackexchange.com/questions/3835/alternative-to-vs-alternative-for -->
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
.
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 thehref
attribute via the$state.href()
method.