One of the major reasons for AngularJS' popularity is directives and they are everywhere. We have used them throughout the book without putting much thought into how they actually function and how to create one. Directives, together with data-binding infrastructure, make true view-logic separation possible.
Consuming directives is easy, but creating one is a complex task and requires an understanding of the inner workings of the framework and directives itself. This chapter will give an insight into the world of directives and in the process you will build some useful directives for the Personal Trainer app.
The following topics will be covered in this chapter:
ng-click
directive in this context.$compile
and $parser
, and learn to utilize them to build directives.Let's get started.
We know what directives are and we have used them all along: ng-click
, ng-show
, ng-style
, and ng-repeat
are all directives. These are JavaScript objects defined using the directive
function of the Module API. Once constructed, they are either attached to existing HTML elements or extend the existing HTML vocabulary with new elements/tags.
Directives have been conceptualized and incorporated into the framework in such a way that they allow the integration of controllers and views naturally and in a less verbose manner. It's the job of a directive to orchestrate the interaction between the controller and the view, keeping the separation of concerns intact.
From a functional standpoint, there are broadly two families of directives:
ng-click
, ng-show
, and ng-style
.$modal
service. The $modal
service used in show history and YouTube video sections internally injects directives: modal-backdrop
and modal-window
into the HTML. These two directives actually provide the dark backdrop and the basic window layout for modal dialog.ng-repeat
, ng-if
, ng-include
, and ng-view
directives are some of the examples.In the next section, we will build directives that showcase working of the preceding types. Let's start our discussion with understanding how directives are structured.
52.14.17.40