【问题标题】:How to include <tr> element in angular directive (transclude)?如何在角度指令(transclude)中包含 <tr> 元素?
【发布时间】:2016-11-24 06:17:03
【问题描述】:

我想包括&lt;tr&gt;&lt;td&gt;,显然我不能用指令来做到这一点。它一直忽略&lt;td&gt;&lt;td&gt;,就好像它们不存在一样。这是我想要完成的:

<my-table>
   <tr>
     <td>hello</td>
     <td>world</td>
   </tr>
</my-table>

这里是javascript:

angular.module('app', [])
.controller('Controller', ['$scope', function($scope) {

}])
.directive('myTable', function() {
   return {
     restrict: 'E',
     transclude: true,
     templateUrl: 'my-table.html'
   };
});

我的表.html:

<table ng-transclude>

</table>

上面的代码导致:

<my-table class="ng-isolate-scope"><table ng-transclude="">

   hello  <-- no <tr> nor <td> here just plain text
   world

</table></my-table>

示例:PLUNKR

【问题讨论】:

  • 那些&lt;tr&gt;&lt;td&gt;应该放在my-dialog-close.html里面。
  • @RogerNg 这正是我不想要的。我想要一个可定制的&lt;tr&gt;,但我希望它被我的指令包装。将其作为&lt;table&gt;的替代品@
  • 没有表格的 tr 将是无效的 html。这就是将其作为文本而不是 html 的原因
  • 总结了这一切,这就是我之前在 plunkr 代码中收到警告的原因。谢谢

标签: javascript html angularjs


【解决方案1】:

这不是一个嵌入问题。这是无效 html 的问题,因为没有表格的&lt;tr&gt; 是无效的。所以角度来自浏览器text,而不是 DOM 元素。所以你需要在 html 中有&lt;table&gt; 标签:

  <my-table>
  <table>
      <tr>
       <td>hello</td>
       <td>world</td>
     </tr>
  </table>
  </my-table>

然后您将能够访问浏览器创建的tbody 元素以及tr 的链接功能并对其进行处理:

  link: function(scope,element,attrs,ctrls,transclude) {
    var html = transclude();
    element.find('table').append(html[1].firstElementChild);
  }

或像您一样在模板中使用ng-transclude。但是,我可能假设您稍后会想要重用已嵌入的部分,因此在链接函数中访问它对我来说更有意义。

【讨论】:

    【解决方案2】:

    添加到我之前的评论中,如果你想使用 ng-trasclude,你可以实现类似这样的效果

    angular.module('app', [])
      .controller('Controller', ['$scope', function($scope) {
    
      }])
      .directive('myTable', function() {
        return {
          restrict: 'E',
          transclude: true,
          scope: {
            'close': '&onClose'
          },
          templateUrl: 'my-dialog-close.html'
        };
      });
    

    模板

    index.html

    <my-table>
        <table>
         <tr>
           <td>hello</td>
           <td>world</td>
         </tr>
        </table>
      </my-table>
    

    Plunker:https://plnkr.co/edit/u85h0sJL50k2gESfI6RT?p=preview

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多