【问题标题】:Getting custom directive inside div在 div 中获取自定义指令
【发布时间】:2015-07-22 04:44:50
【问题描述】:

我希望开始划分我的代码。我从一个基本表开始,但无法弄清楚为什么指令在其分配的容器上方输出。

我从一个简单的指令开始

var app= angular.module('myApp');

app.directive("productItem", function() {
    return {
        restrict: 'EA',
        replace: false,
        // transclude: true,
        scope: false,
        templateUrl: 'templates/tableWrapper.html'

    }
}); 

我已经缩小了我的模板以开始。所以我硬编码了一些值

<td>Bob </td>
<td>10006 </td>

在分配的父 div 中,我正在附加标签

<table class="table table-striped"  >
    <tr>
      <th>Name</th> <th>Quantity</th> 
    </tr>
    <tr>

    <tr>
      <product-item></product-item>
    </tr>
  </table>

我最初是从 replace: true 开始的,假设更改 product-item 标记将采用表格形式并适合表格。但是,模板适合表格之外。

还有 require: true 我得到一个错误

Template for directive 'productItem' must have exactly one root element. templates/tableWrapper.html

根据我阅读的内容,当我希望产品项目适合产品表时,transclude 会很有用。所以现在它不会有帮助。

我试图参考这篇文章Angularjs templateUrl fails to bind attributes inside ng-repeat。但是,当我开始动态创建数据时,这更像是我的下一步。

【问题讨论】:

  • 请提供一个 JSFiddle,以便我可以查看其他编码,包括您的 JavaScript 和您引用的确切 Angular 代码。

标签: javascript angularjs angularjs-directive


【解决方案1】:

在处理表格行(&lt;tr&gt; 元素)内的内容时存在错误/功能。如您所见,您不能在表格行内指定自定义元素,否则它们将被移出表格。

改为在属性样式中使用您的指令,如下所示:

...
restrict: 'A', // A for attribute only
...

在你的模板中,做这样的事情:

<tr>
  <td product-item></td>
</tr>

这应该适合你。

另外,请确保您保留replace:false

【讨论】:

  • 感谢您指出这一点。我以为我被这个 bug 覆盖了,因为我在模板中创建了 td。
猜你喜欢
  • 2016-11-04
  • 1970-01-01
  • 2012-12-14
  • 2012-09-04
  • 2020-08-02
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多