Tushar Kapoor
Tushar Kapoor

Reputation: 33

Dynamically adding rows to a table using attribute directive in AngularJs

I need to display a table on my HTML page. The table will contain multiple rows. On clicking the '+' icon of a row(let's call it R1), I call an attribute directive to fetch data and display it in a new row(R2) which should be added below the clicked row(R1).

But currently, the data isn't getting displayed and I get a blank row(R2) added below the clicked row(R1).

The code for directive is:

angular.module(
  "app", []
).controller(
  'Ctrl', [
    "$scope",
    function(
      $scope
    ) {
      $scope.items = {
        "first": {
          "name": "item1"
        },
        "second": {
          "name": "item2"
        },
        "third": {
          "name": "item3"
        }
      };
      $scope.showData = false;

    }
  ]
).directive(
  "expandItem", [
    function() {
      return {
        link: function($scope) {
          $scope.showRdoData = false;

          $scope.subitems = {
            "fir": {
              "names": "subitem1"
            },
            "sec": {
              "names": "subitem2"
            },
            "thd": {
              "names": "subitem3"
            }
          };
        },
        restrict: 'A',
        replace: false,
        template: '<tr ng-repeat="row in ::subitems">' +
          '<td style="background-color: red"><i class="fa fa-fw fa-{{showRdoData ? \'minus\' : \'plus\'}}"></i></td>' +
          '<td style="background-color: blueviolet">{{::row.names}}</td></tr>'
      }
    }
  ]
);

Can someone help me in getting the data displayed in the table please? The code is present at JSFiddle. Please let me know if the question isn't clear. I will try to rephrase it if needed.

Upvotes: 2

Views: 1101

Answers (1)

Jaicob
Jaicob

Reputation: 60

So the reason you were having issues was because the ngIf directive does not play well with ngRepeat by passing showData to the directive via an isolate scope you can move the ngIf to the <td>'s and achieve the expected behavior. Here is a link to a working fiddle

HTML

<body ng-app="app">
  <table ng-controller="Ctrl">
    <thead>
      <th>Col1</th>
      <th>Col2</th>
    </thead>
    <tbody>
      <tr ng-repeat-start="item in items" ng-click="showData = !showData">
        <td><i class="fa fa-fw fa-{{showData ? 'minus' : 'plus'}}"></i></td>
        <td>{{item.name}}</td>
      </tr>
      <tr ng-repeat-end expand-item show-data="showData"></tr>
    </tbody>
  </table>
</body>

Modified Directive Values

replace:true,
template: '<tr ng-repeat="row in ::subitems">' +
            '<td ng-if="showData" style="background-color: red"><i class="fa fa-fw fa-{{showRdoData ? \'minus\' : \'plus\'}}"></i></td>' +
            '<td ng-if="showData" style="background-color: blueviolet">{{::row.names}}</td>' + 
          '</tr>'

Upvotes: 1

Related Questions