Custom Directives and Directive Controllers
In addition to Angular's broad options for directives, you can create custom directives for pieces of HTML that you wish to re-use throughout your page.
The "ng-include" Directive
The ng-include directive lets you re-use custom HTML, but will send a request to the server for the included file.
{{ product.name }}
<em class="pull-right">${{ product.price}}</em>
To include this in your normal code, use ng-include.
<h3 ng-include="'include-file.html'"></h3>
The ng-include directive expects a variable containing the filename, so the single quotes turn the hard-coded filename into something that can be evaluated.
app.directive('productTitle', function() { return { restrict: 'E', templateUrl: 'include-file.html' }; });
The restrict of 'E' defines the type of the directive. E is for a new HTML element.
<product-title></product-title>
Some elements don't like self-closing tabs, so don't use them.
Attribute vs. Element Directives
Attribute directives should be used for mixin behaviors (ie tooltips), and element behaviors for UI widgets. I'm writing this down as a note, but I'm not sure exactly what represents a mixin behavior. Hopefully I'll be able to write a post about that distinction later.
When defining attribute directives, you use a restrict of 'A'.
So directive controllers are really cool, and eliminate some of the clunkiness I complained about in Angular, Continued. Directive controllers are defined by adding a "controller" to the directive definition.
app.directive('customDirective', function() { return { restrict: 'E', templateUrl: 'custom-directive.html', controller: function() { ... }, controllerAs: controllerName }; });
The directive controllers functionality makes it much easier to break your code into neatly contained modules, and modules make writing large javascript projects much easier.
Furthermore, custom directives coupled with directive controllers let you see what your HTML is trying to do just by reading the HTML.