表的angular指令:使用ng-bind-html绑定transcluded元素



我正在尝试编写一个类似以下的通用表指令:

<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-table模板类似于:

<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-table和h-column。h-table指令使用一个指令控制器,这两个指令都将使用该控制器。h-column指令将使用此控制器将列添加到表中,并获取行/列的值。

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

.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-column指令接收h-table的控制器。它使用transclude获取它的内容,并将此内容保存在col对象中,以便在之后绑定它

.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-table指令:

.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-column的内容放在td标签中。因此,我调用getContentOrValueFor函数来获取h-column指令中的内容。

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

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

但是如果这个内容是一个html标签,比如:

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

我得到错误"html.indexOf不是一个函数">

我怎样才能做到这一点??

我认为这是由于不包括ngSanatize造成的。请参阅:https://docs.angularjs.org/api/ng/directive/ngBindHtml

最新更新