Nested Directive Virtual Groups in Angular JS

In my last post I went over a new unreleased feature of Angular JS, Directive Virtual Groups. This allows you to append -start to a directive allowing it to span multiple DOM elements. You can terminate the multi-DOM element by applying -end to the same directive. For example:

<tr ng-repeat-start="order in orders">
<tr ng-repeat-end>

This would iterate over a series of orders and render two TR tags for each order. The ng-repeat-start indicates the ng-repeat condition as well as a starting flag for angular. Everything following that (including it’s TR tag) is part of the template, until it reaches a ng-repeat-end. That element is then included and is considered the terminating element.

Well what about multiple -start and -end tags nested? I decided to try to play around with ng-click in addition to ng-repeat. Imagine if we wanted to make only the number and price table cells clickable. We want those cells to call a function named ‘calculate’. I could easily modify the above example to be:

<tr ng-repeat-start="order in orders">
<tr ng-repeat-end>
  <td ng-click-start="calculate(order)">{{order.number}}</td>
  <td ng-click-end>{{order.price}}</td>

While this may seem complicated, the syntax basically says

  1. start the repeat process at the first TR tag
  2. terminate the template at the second tag (where ng-repeat-end) comes in
  3. In the second TR tag, start defining a clickable region ng-click-start
  4. Apply click region to first and second TD until ng-click-end is found

Notice how I only defined the target of the ng-click once, but both elements are now clickable and will call the calculate method. Pretty cool and DRY!

As a reminder, this feature is in the code base but has NOT made it to the stable release of Angular. So it might not work for you unless you have the latest build form their Github repository.
works on my machine


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s