1

我想写这样一个通用的表指令:的表角指令:绑定transcluded元素与NG绑定,HTML

<h-table rows="customers"> 
    <h-column field="Id"> 
    <a ng-click="editCustomer(row.Id)">{{row.Id}}</a> 
    </h-column> 
    <h-column field="Name"> 
    </h-column> 
</h-table> 

这将产生下面的HTML:

<table> 
    <tr> 
    <th>Id</th> 
    <th>Name</th> 
    </tr> 
    <tr> 
    <td> 
     <a ng-click="editCustomer(1)">1</a> 
    </td> 
    <td> 
     Alexandre 
    </td> 
    </tr> 
    ... 
</table> 

我的H-表模板是一样的东西:

<script type="text/ng-template" id="hTableTemplate.html"> 
    <div> 
     <div ng-transclude id="limbo" style="display: none"></div> 
     <table> 
      <tr> 
       <th ng-repeat="col in cols">{{col.field}}<th> 
      </tr> 
      <tr ng-repeat="row in rows"> 
       <td ng-repeat="col in cols"> 
        // Here I need to put the content of h-column directive 
        // if it exists, or just bind the value for the column 
        <span ng-bind-html="getContentOrValueFor(row, col)" /> 
       </td> 
      </tr> 
     <table> 
    </div> 
</script> 

所以我需要创建两个指令:H-表和h列。 h-table指令使用一个指令控制器,这个指令将被这两个指令使用。 h列指令将使用此控制器将col添加到表中并获取行/列的值。

到目前为止,这是我的指令的控制器:

.controller("hTable", function ($scope, $element, $attrs, $compile) { 
    $scope.cols = []; 

    this.addCol = function (col) { 
     $scope.cols.push(col); 
    }; 

    $scope.getContentOrValueFor = function (row, col) { 
     // MY PROBLEM IS HERE! I will explain below ... 
     return col.content && col.content.html() ? col.content.html() : row[col.field]; 
    }; 
}) 

我的H-列指令输入h表的控制器。 它使用transclude得到它的内容,并保存山坳对象的内部此内容,之后将其绑定:

.directive("hColumn", function() { 
    return { 
     restrict: "E", 
     require: "^hTable", 
     transclude: true, 
     scope: { 
      field: "@", 
     }, 
     link: function(scope, element, attrs, hTableController, transclude) { 
      var col = {}; 
      col.field = scope.field; 
      col.content = transclude(); // <-- Here I save h-column content to bind after 
      hTableController.addCol(col); 
      ... 
     } 
    }; 
}) 

最后:)我的H-表指令:

.directive("hTable", function() { 
    return { 
     restrict: "E", 
     scope : { 
      rows: "=" 
     }, 
     controller: "hTable", 
     require: "hTable", 
     replace: true, 
     transclude: true, 
     templateUrl: "hTableTemplate.html", 
     link: function(scope, element, attrs, hTableController) { 
     ... 
     } 
    }; 
}) 

我需要把^ h td标签内的列内容。因此,我调用getContentOrValueFor函数来获取h-column指令内的这个内容。

如果没有内容,那么我将绑定该字段的值。

如果h列的内容类似{{1 + 2 + 3}}(它会告诉我6,没关系),它可以正常工作。

但是,如果这个内容是HTML标签,如:

<a href="somelink">test</a> 

我得到的错误“html.indexOf是不是一个函数”

我怎样才能做到这一点?

回答