KennyE KennyE - 3 months ago 30
AngularJS Question

AngularJS displaying different number of td elems in each tr using ng-repeat and ng-if

I am trying to create a table in angularjs where the number of td elements per row of the table varies. Sometimes there will be one td element spanning two columns and sometimes there will be two td elements.

The example code below is giving me the following table:

ID     Item 1   This is Item 2!

ID     Item 2   This is Item 2!

ID     Item 3   This is Item 2!

ID     Item 4   This is Item 2!


However, I want the table to look like this:

ID     Item 1

This is Item 2!

ID     Item 3

ID     Item 4


The angular code:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link href="bootstrap.css" rel="stylesheet" />
<script src="angular.js"></script>
<script>
var myApp = angular.module('myApp', []);

myApp.controller("TabCtrl", function($scope) {
$scope.items = ["Item 1", "Item 2", "Item 3", "Item 4"]

});
</script>
</head>
<body>
<div ng-controller="TabCtrl">
<table class="table">
<tr ng-repeat="item in items">
<div ng-if="item != 'Item 2'">
<td>ID</td><td>{{item}}</td>
</div>
<div ng-if="item == 'Item 2'">
<td colspan="2">This is Item 2!</td>
</div>
</tr>
</table>
</div>
</body>
</html>


Why is the ng-if not selecting only one of the divs for each row?

Answer

This is what I saw, when I pasted your html into a plunker:

voodoo mode

div tags aren't allowed inside tr tags, and td tags are not allowed inside div tags. Probably, the div tags are getting skipped completely, and then the ng-ifs are lost with them.

You don't need the div tags. Just put the ng-ifs directly on the td tags:

<table class="table">
  <tr ng-repeat="item in items">
    <td ng-if="item != 'Item 2'">ID</td>
    <td ng-if="item != 'Item 2'">{{item}}</td>
    <td ng-if="item == 'Item 2'" colspan="2">This is Item 2!</td>
  </tr>
</table>
Comments