0

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?

KennyE
  • 513
  • 6
  • 15

3 Answers3

2

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>
Community
  • 1
  • 1
j.wittwer
  • 9,497
  • 3
  • 30
  • 32
0

your ng-if expressions are missing a closing single quote

Vlad Gurovich
  • 8,463
  • 2
  • 27
  • 28
  • I've updated the ng-if expressions to include closing single quotes but the issue isn't resolved. – KennyE Apr 21 '14 at 22:38
0

You need to have ng-if inside td only

<!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">

          <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>
  </div>
</body>
</html>
anik
  • 155
  • 1
  • 17