Search code examples
angularjsangularjs-ng-repeatangularjs-ng-if

How to use ng-if with tr tag along with ng-repeat?


Can someone help me on this? Below is my code and the problem explanation.

<table>
 <thead>
   <tr>
     <th>Icon</th>
     <th>Name</th>
     <th>Details</th>
   </tr>
 </thead>

 <tbody ng-repeat="category in editor.categories">
    <tr>
      <th>{{category.categoryName}}</th>
    </tr>
    <tr ng-repeat="feature in category.features"> // Question?
       <td>{{feature.iconImg}}</td>
       <td>{{feature.featureName}}</td>
       <td>{{feature.details}}</td>
     </tr>
     <tr ng-if="feature.id==1"> // condition 1
     </tr>
     <tr ng-if="feature.id==2"> // condition 2
     </tr>
  </tbody>
</table>

Now, let me explain the problem. I have a group of Categories. Each and every category as a group of features.

Now my question is, how can these feature for every category can be displayed based on the ng-if condition. i.e., the <tr> at condition 1 should be displayed only if feature.id==1 and same goes for condition 2 as well only if feature.id==2.

Q. How do I include my ng-if condition based on the different conditions?

Your help is very much appreciated.


Solution

  • Use both ng-if and ng-repeat within one tag:

    <tr ng-repeat="feature in features"
        ng-if="feature.id === 1" >
    </tr>
    

    Or, if you want to conditionally display some templates you may use ng-switch for example:

    <tr
        ng-repeat="feature in features"
        ng-switch="feature.id" >
        <span ng-switch-when="1"></span>
        <span ng-switch-when="2"></span>
    </tr>