【问题标题】:How to access the ng-repeat item from an inner custom directive如何从内部自定义指令访问 ng-repeat 项目
【发布时间】:2016-02-21 22:39:07
【问题描述】:

我在 ng-repeat 中的自定义指令有问题。我试图绑定的值之一总是未定义:

项目列表模板

<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 模板

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

指令

.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);
    }
  };
}])

关于我需要做什么才能从我的指令中的 ng-repeat 访问 item 绑定有什么想法吗?

一般来说,使用 ng-repeat 时是否需要创建冗余属性绑定:

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

在我的指令中,我使用"="进行列绑定,所以我需要模板中的column="column"吗?

谢谢

【问题讨论】:

  • 您期望一个名为 problem 的属性,但调用者传递了一个名为 item 的属性。
  • 抱歉,这是一个复制粘贴错误。应该是无处不在的项目。更新。谢谢。

标签: angularjs


【解决方案1】:

&lt;tr&gt; 标记只能包含&lt;td&gt;&lt;th&gt; 元素,因此以下结构不是有效的 HTML,并且不会以您期望的方式被浏览器解析(有或没有 AngularJS)。

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

您可以通过检查当前解决方案生成的 HTML 来确认这一点。

如果您想在 &lt;td&gt; 元素上放置指令,您应该将其更改为类或属性,例如

HTML:

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

JS:

restrict: 'A',

Simplified Fiddle

【讨论】:

  • 啊,是的,一些头疼和搜索最终让我明白了这一点。感谢您的确认。一旦解释就有意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多