实现空元素以角度

时间:2017-05-05 13:19:30

标签: angularjs angularjs-directive html-table

我必须从第三个开始重复列。由于无法在tr中放入另一个标签,因此在此示例中我可以使用的hybrid元素是什么?

    <table>
        <tr>
           <th colspan='2'>Category</th>
           <th ng-repeat='p in ps' colspan='3'>{{p.id}}</th></tr>
        <tr ng-repeat='c in cats'>
            <td>{{c.code}}</td>
            <td>{{c.label}}</td>
         <hybrid ng-repeat='p in ps'>
            <td>{{p.quantity}}</td>
            <td>{{p.cost}}</td>
            <td>{{p.quantity*p.cost}}</td>
         </hybrid>                
        </tr>
    </table>

我没有成功尝试类似

的内容
   app.directive("hybrid",function($compile) {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {              
            element[0].outerHTML = element[0].outerHTML;
            $compile(element.contents())(scope);
          }
       }
    });

我错过了什么?

2 个答案:

答案 0 :(得分:0)

我完全不了解您的要求,但您可以在<span>内使用重复的<td>。我在this fiddler

尝试了类似的东西

<强>更新

Fiddle link仅包含<td>且未使用指令。使用*登录小提琴来分隔数据

答案 1 :(得分:0)

我终于解决了这个问题。

  • 我创建了一个replace-me指令来替换内部span
  • 我将ng-repeat添加到了td,而不是将其替换为htmls

请参阅this fiddle

   <table>
   <tr>
        <th colspan='2'>Category</th>
        <th ng-repeat='p in ps' colspan='3'>{{p.id}}</th>
  </tr>
  <tr ng-repeat='c in cats'>
      <td>{{c.code}}</td>
       <td>{{c.label}}</td>
      <td colspan='3' ng-repeat='p in ps' data-hybrid>
    <span data-replace-me data-replace-with-tag='td'>{{p.quantity}}</span>
    <span data-replace-me data-replace-with-tag='td'>{{p.cost}}</span>
    <span data-replace-me data-replace-with-tag='td'>{{p.quantity*p.cost}}</span>
      </td>
  </tr>
 </table>

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

    myApp.directive("hybrid", function($compile) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          var el = angular.element(htmls);
          $compile(el.contents())(scope);
          element.replaceWith(el);
        }
      }
    });
    myApp.directive("replaceMe", function($compile) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          var htmls = element.html(),
            el;
          if (attrs.replaceWithTag) {
            htmls = "<" + (attrs.replaceWithTag) + ">" + element.html() +         "</" + (attrs.replaceWithTag) + ">";
          }
          el = angular.element(htmls);
          $compile(el.contents())(scope);
          element.replaceWith(el);
        }
      }
    });

    myApp.controller('MyCtrl', function MyCtrl($scope) {
      $scope.ps = [{
        id: 2,
        quantity: 3,
        cost: 10
      }, {
        id: 5,
        quantity: 7,
        cost: 20
      }];
      $scope.cats = [{
        code: "mycode",
        label: "mylabel"
      }]
    });