14

Is it possible to add stuff to the markup based on condition? Like in this example, when I want to add td only on the first iteration (only for the first element of myData)?

<tr ng-repeat="m in myData">
   <td>{{m.Name}}</td>
   <td>{{m.LastName}}</td>

   @if myData.indexOf(m) = 0 then // something like that
   <td rowspan ="{{m.length}}">
      <ul>
        <li ng-repeat="d in days">
           {{d.hours}}
        </li>
      </ul>
   </td> 
</tr>
iLemming
  • 34,477
  • 60
  • 195
  • 309

2 Answers2

16

Yes, AngularJS has 2 directives for this occasion:

  • The ng-show / ng-hide family of directives can be used to hide (by using display CSS rules) parts of the DOM three based on a result of evaluating an expression.
  • If we want to physically remove / add parts of the DOM conditionally the family of ng-switch directives (ng-switch, ng-switch-when, ng-switch-default) will come handy.

At the end of the day both solutions will give the same visual effect but the underlying DOM structure will be different. For simple use cases ng-show / ng-hide is probably OK, but larger portions of the DOM should be treated with ng-switch.

For the use case from this question I would advice using ng-switch.

pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286
  • 1
    Just to add. $index have the current index of the item, so ng-show="$index == 0" – Renan Tomal Fernandes Nov 19 '12 at 20:19
  • 4
    As of Angular 1.1.5, you can also use `ng-if="your expression"` directive. You add it as an attribute to any element. If it validates to true, it adds that element to the dom. – EnigmaRM Jul 15 '13 at 22:05
3

The best solution should be:

<tr ng-repeat="m in myData">
   <td>{{m.Name}}</td>
   <td>{{m.LastName}}</td>

   <td ng-if="$first" rowspan="{{myData.length}}">
       <ul>
           <li ng-repeat="d in days">
               {{d.hours}}
           </li>
       </ul>
   </td> 
</tr>
Jeff Tian
  • 5,210
  • 3
  • 51
  • 71