Nested directives
Sometimes, you need to have nested directives. For example, you need to display an array of an array of items. With two levels of nested arrays, it is easy to implement such thing. However, if you need to have a dynamical level of nested arrays, it is not as obvious as implementing two levels of nested arrays.
There are two ways (in my knowledge) to build nested directives.
- Using the directive
ng-include
and one custom directive - Using two custom directives
1 - Using the directive ng-include
and one custom directive
Let’s say, we want to display the given data in nested bullets list:
|
|
First, let’s create our index.html
with a our custom directive. We will name it items
:
|
|
Then let’s create a directive.js
that contains the code for the custom directive:
|
|
- restrict:
'E'
to tell angular to match this directive to any HTML tag matchingitems
- templateUrl: the template URL of the directive
- scope: the scope of the directive
Our template items.html
looks like this:
|
|
We use the ng-include
to include the other template item.html
.
Moreover, we use ng-repeat
on the array of items in order to display the bullets list of the items.
Our template item.html
looks like this:
|
|
Again, in this template, we use the directive ng-include
that points on the same template.
ng-include
recursively FTW!
That’s it! You have your nested directive.
Complete code on Plnkr.
2 - Using two custom directives
No need to reinvent the wheel, someone already has found this solution.