Directives are a core AngularJS feature. From the framework directives you will use every day like
ng-repeat, to your own custom directives that allow you to extend the vocabulary of the browser, if you are learning AngularJS, you need to have a solid understanding of Directives.
Because directives are so important, we've recorded quite a few lessons on the topic. If you've got a couple of hours to spare, you will be well on your way to directive mastery.
If you are just starting out, you might want to read New to AngularJS? Start learning here.
Writing your first directive
Directives can be very simple. These two lessons will get you started learning so that you can graduate to more complex directives.
Directives come in a couple of main flavors. The first is "behavior" style directives. These directives are attached to to HTML elements and provide some sort of augmented functionality.
When you define a directive you get access to the attrs object by declaring it as a dependency in the link function. The attrs object will contain the normalized attributes and their corresponding values declared on the element which contains the directive in the html. So if you set a value on your directive attribute (myDirective="value"), you can access this value in your directive configuration by accessing attrs.myDirective, as this contains the value set in the html for myDirective.
Directives can be restricted to DOM elements, attributes, CSS class names, or even comments. This is useful for defining the type of directive you are creating. A behavior directive will likely be an attribute or CSS class. No directive should ever use the comment style!
By default AngularJS directives can be used with elements, attributes, classes, and comments. Many times we want to restrict it to one or more of those to control how a directive will be used. This lesson digs into how and why to use Directive restrictions.
Isolate scope can be a tough concept to understand when you are first starting out with AngularJS. Since directives are reusable, sharing $scope can create undesirable behavior with shared state.
By isolating scopes you are able to control how and when your directives will share state with controllers and other directives.
This episode is explaining the naming conventions behind for the arguments passed to the factory functions for controllers, directives, linking functions, etc., its implications in regard to Angular’s dependency injection, minification side effects on arguments, and how to prevent them.
Putting it all together
With the basics of AngularJS directives in your tool belt, you are ready to build something a bit more interesting.
You are about half-way through the egghead.io directive lessons. Stay tuned for another guide that will get into more advanced topics such as transclusion and unit testing your directives!