【问题标题】:Angular directive doesn't work properly inside an HTML tableAngular 指令在 HTML 表格中无法正常工作
【发布时间】:2014-09-26 00:30:11
【问题描述】:

我正在尝试使用 AngularJS (1.2) 指令在 HTML 表格中创建行单元格,但我不明白为什么 Angular 将指令结果作为“body”的第一个子元素插入,而不是替换原始指令元素?

这是 HTML 标记:

  <body ng-app="myApp" ng-controller="MainCtrl">
    <table>
      <thead>
        <tr>
          <th>col1</th>
          <th>col2</th>
          <th>col3</th>
          <th>col4</th>
        </tr>
      </thead>
      <tbody>
        <my-directive></my-directive>
      </tbody>
    </table>
  </body>

还有指令:

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.data = ['value1','value2','value3','value4'];
});

app.directive('myDirective', function () {
    return {
        restrict: "E",
        replace: true,
        scope:false,
        link: function (scope, element) {
            var html = angular.element('<tr></tr>');
            angular.forEach(scope.data, function(value, index) {
                html.append('<td>'+value+'</td>');
            });
            element.replaceWith(html);
        }            
    };
});

请使用下面的 Plunker 链接查看结果: http://plnkr.co/edit/zc00RIUHWNYW36lY5rgv?p=preview

【问题讨论】:

  • 为了替换工作,使用模板。
  • 我们不能总是使用模板属性(我的代码已经为示例进行了简化)。此外,replace 属性可以很好地与其他标签配合使用。我只是 html-table 的问题。
  • 浏览器会自动丢弃表格中不正确或意外的标签。为了使您的指令有效,请将其用作属性而不是元素。

标签: angularjs html-table directive


【解决方案1】:

如果你不将指令限制为一个元素,它似乎会更好:

app.directive('myDirective', function () {
    return {
        restrict: "A",
        replace: true,
        scope:false,
        link: function (scope, element) {
            var html = angular.element('<tr></tr>');
            angular.forEach(scope.data, function(value, index) {
                html.append('<td>'+value+'</td>');
            });
            element.replaceWith(html);
        }            
    };
});

<table>
  <thead>
    <tr>
      <th>col1</th>
      <th>col2</th>
      <th>col3</th>
      <th>col4</th>
    </tr>
  </thead>
  <tbody>
    <tr my-directive></tr>
  </tbody>
</table>

【讨论】:

    猜你喜欢
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    相关资源
    最近更新 更多