Apr 28 2015

AngularJS Directives (part 2)

What are Directive types and how to choose one?

Different Directive Types
Directives can be 3 different types.

Use elements if your directive is a component, meaning it has control over the entire template it is rendering.

//Create a directive called 'Awesome'
app.directive('awesome', function(){
	return {
		// Specify the directive as 'ELEMENT'
		restrict: "E",
		template: "<div>My Awesome Text</div>"
Use this when you're adding or modifying behavior to an existing component or container.
<div awesome></div>
// Specify the directive as 'ATTRIBUTE'
restrict: "A"
Classes aren't recommended by Angular because classes are used for multiple purposes including CSS and it makes it difficult to find your directives in your HTML.
<div class="awesome"></div>
// Specify the directive as 'CLASS'
restrict: "C"
There is actually a 4th type of directive (for all you nitpickers out there) but Angular encourages developers to use the other options. According to Angular's website:
"Best Practice: Comment directives were commonly used in places where the DOM API limits the ability to create directives that spanned multiple elements (e.g. inside table elements). AngularJS 1.2 introduces ng-repeat-start and ng-repeat-end as a better solution to this problem. Developers are encouraged to use this over custom comment directives when possible."

Multiple types
Eventhough it's best practice, you don't necessarily have to specify just one type. You can mix and match and Angular will accept all specified types:
// Specify the directive as 'ATTRIBUTE or ELEMENT'
restrict: "AE"

// Specify the directive as 'ELEMENT or CLASS'
restrict: "EC"

// Specify the directive as 'ATTRIBUTE, ELEMENT or CLASS'
restrict: "AEC"
By default, if you don't specify a type Angular assumes you mean ELEMENT and ATTRIBUTE.

In Part 3 I'll show you how to specify your Directive's template.