D.C.
D.C.

Reputation: 15588

How to access the ng-repeat item from an inner custom directive

I am having a problem with my custom directive inside an ng-repeat. One of the values I'm trying to bind always ends up being undefined:

ItemList template

<div>
  <table>
    <thead>
      <tr>
        <th ng-repeat="column in itemContext.columns">{{column.heading}}</th>
      </tr>
    </thead>
    <tbody>
      <!-- Also experimented leaving item='item' out as well -->
      <tr item="item" ng-repeat="item in itemList.items">
        <item-column item="item" column="column" ng-repeat="column in itemContext.columns"></item-column>
      </tr>
    </tbody>
  </table>
</div>

ItemColumn Template

<!-- Problems here because item is undefined -->
<td ng-class="columnClasses(column, item)">{{column.itemField(item)}}</td>

Directives

.directive('itemColumn', ["$rootScope", function($rootScope) {
  return {
    restrict: 'E',
    replace: 'true',
    templateUrl: '/templates/itemColumn.html',
     scope:{
       item: "=",
       column: "="
    },
    link: function(scope, element, attrs) {

      console.log("-- Loading item column --");
      // sope.column is what I would expect, but scope.item is undefined
      console.log(scope);
    }
  };
}])

Any ideas on what I need to do to be able to access the item binding from ng-repeat in my directive?

In general, do I need to create a redundant attribute binding when using ng-repeat:

<item-column item="item" column="column" ng-repeat="column in itemContext.columns"></item-column>

In my directive I use "="for the column binding, so do i need the column="column"in the template?

Thanks

Upvotes: 0

Views: 149

Answers (1)

sheilak
sheilak

Reputation: 5873

The <tr> tag can only contain <td> and <th> elements, so the following structure is not valid HTML and will not be parsed in the way you are expecting by the browser (with or without AngularJS).

<tr>
    <item-column></item-column>
</tr>

You can confirm that by inspecting the generated HTML of your current solution.

If you want to put a directive on a <td> element, you should change it to a class or an attribute e.g.

HTML:

<tr>
    <td item-column item="item" ...></td >
</tr>

JS:

restrict: 'A',

Simplified Fiddle

Upvotes: 1

Related Questions