Angular 1.x Directives

Last modified: 
Friday, October 28th, 2016

Running notes on Angular directives.

Creating Directives

Best Practice: Prefix directives to avoid future conflicts with new HTML elements. (Though, realistically, you'll probably have completely rebuilt your site in some new framework long before HTML7 comes out.) Don't prefix directives with 'ng', because that's in Angular's namespace.

Restrict Option

  • A will match on attribute name, e.g., <div my-dir="exp"></div>
  • E will match on element name, e.g., <my-dir></my-dir>
  • C will match on class name, e.g., <!-- directive: my-dir exp -->
  • M will match on comment, e.g., <div class="my-dir: exp;"></div>
  • AEC mix and matches restrictions to match either attribute or element or class name

Best Practice: Prefer matching directives to attributes and elements.

When to use E vs A

When creating a directive that makes sense as a stand-alone element, allow restrict E (custom element) and optionally restrict A (custom attribute). Generally, if it could be its own control, E is appropriate. General guideline is allow EA but lean towards implementing as an element when it's stand-alone and as an attribute when it enhances its existing DOM element.
https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#...

Recommended

<!-- E, directive defines an entire element -->
<my-dir></my-dir>

<!-- A, directive augments the existing div -->
<div my-dir></div>


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.