AngularJS directive multiple element

How to get AngularJS directive multiple element

You probably know there exists opening ng-repeat-start and finishing directive ng-repeat-end like:

<ul>
 <li ng-repeat-start="user in users">
   {{user.firstName}}
 </li>
 <li ng-repeat-end>
   {{user.firstName}}
 </li>
</ul>

You would think it is a specially made directive that works that way but actually it is not. It is part of any directive so you can use it inside your too. When you create new directory and inside you factory function you need to return an object with multiElement options set to true. This way it will behave same as ngRepeat directive over multiple non nested fields. Small excerpt from ngRepeat.js file denoting this:

var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  ...
  return {
    restrict: 'A',
    <strong>multiElement: true,</strong>
    transclude: 'element',
    priority: 1000,
    terminal: true,
    ...
   }
}];

From native angularJS directive there are few more directives that support multi element spanning. They are ngIf, ngShow, ngHide and ngSwitch. So by adding multiElement to your custom directive you can make to transclude over angularjs directive multiple elements at the same time. This also comes handy because you can do nesting of multiple elements if they are contained inside another one.

Related Post

2 Replies to “AngularJS directive multiple element”

  1. @disqus_DpH5LVDFS6:disqus I usually use it for rendering two consecutive divs over a collection where divs are mutually exclusive so on specific actions it switches to another one. Like having a hover action to show another div and doing rotation between them for example.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.