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是不是一個函數」

我怎樣才能做到這一點?

回答