AngularJS Custom Directives
by Nicholas Boll
Who Am I?
- @NicholasBoll
- nicholas.boll@gmail.com
- I'm a Software Engineer at LogRhythm
- I've been using AngularJS for about 6 months
If you use Angular, you already use Directives (ex: ng-model)
{{ message }}
Why make your own?
Angular gives you many powerful directives
jQuery, right?
Directives are:
- A way to expand HTML to be more declarative
- Components or behavior modifiers
- How AngularJS allows you to hook into the DOM
- Complicated
restrict
"E"
Element<my-directive></my-directive>
"A"
Attribute<div my-directive="exp"></div>
"C"
Class<div class="my-directive: exp"></div>
"M"
Comment<!-- directive: my-directive exp -->
WTF?
CSS classes? Comments?!
Comment directives
Mostly used internal for directives like ng-repeat
This is because the Browser parses HTML into DOM and then Angular gets to it
Ex: my-directive creates a td
Class directives
I don't suggest using classes as directives. CSS classes are style-hooks and not obvious that behavior is being added.
Note:
IE8 can't parse Element directives without the help of the document.createElement hack. Stick with attribute directives for IE8 support.
priority
Number
Tells the compiler what order to process directives
Higher numbers get processed first
terminal
Boolean
True means no further compiling will be done of lower priority or child directives
Binding: {{ message }}
Non-binding: {{ message }}
scope
-
Boolean or Object hash
- Set to true for a new scope
- Set to Object hash for an isolate scope
- Scopes have prototypical inheritance
Normal scope: {{ message }}, {{ foo }}
New scope: {{ message }}, {{ foo }}
Isolate Scope
=
Two-way binding between parent and local scope (sharing)
@
One-way (parent to local) binding by interpolation. Ex: hello {{name}}
&
Provides a way to execute an expression in the context of a parent scope.
Parent: {{ message }}
One way: {{ oneWay }}
Two way: {{ twoWay }}
Expression
',
'
Two way:
',
'
expression
'
].join(''),
scope: {
oneWay: '@',
twoWay: '=',
expression: '&'
}
};
});
controller
- Actually more like a Directive Controller
- Should not contain DOM
- Should contain business logic and writing to local scope
- Should be unit-testable without DOM
- Defines an API for directive communication
require
-
String or String[]
- Require a directive controller from the current or parent element
-
(no prefix) is current element, ^ is parent and ? means optional
- Angular will pass required controllers as forth argument to linking function