Directives in AngularJS
Directives is the AngularJS preferred method for building reusable components. This is one of the key features of AngularJS for extending HTML vocabulary. Directives combine the HTML template and the definitions in Controller together. AngularJS has also a lot of built-in directives. The ng-repeat, being used in the last post, is one of them. In fact, Ng prefixed items in templates are all directives. We can also define custom directives in the Controller.
Custom defined directives usually take different forms: as element, as attribute, as class, as comment or as any combination of them. The following code defines directive as element.
After definition, we can use the directive in the html
template:
Similarly, you can define custom directive as attribute:
Then you can use it in html file as follows:
Interestingly, AngularJS can also manipulate DOM in directive definitions. The way is to use the link
option.
The html
template is: