我想制作一个通用指令,用户可以在其中轻松插入页眉和页脚的任何HTML。
这是我的HTML代码:
<datagrid
id="testing"
url="google.com/test">
<header>
<p>header</p>
</header>
<footer>
<p>footer</p>
</footer>
</datagrid>
我想获得内部HTML并自行解析。
directive('datagrid', function () {
return {
restrict: 'E',
templateUrl: 'datagrid.htm',
scope: true,
transclude: true,
link: function ($scope, $el, $attr) {
// get inner HTML, separate header and footer HTML to the variables
// and add that HTML later in the template
}
};
});
我的模板:
<script type='text/ng-template' id='datagrid.htm'>
<table class="datagrid table table-hover table-condensed table-striped">
<thead>
<tr class="top-actions-container">
<!-- INJECT HEADER HTML -->
<th></th>
</tr>
</thead>
<tbody>
<tr>
<!-- RESULTS -->
<td></td>
</tr>
</tbody>
<tfoot>
<tr>
<!-- INJECT FOOTER HTML -->
<td></td>
</tr>
</tfoot>
</table>
</script>
我是Angular的新手,所以我愿意接受其他建议。如果这可能是一个很好的方法吗?
答案 0 :(得分:1)
你可以试试这个:
用法(在主要HTML中)
<datagrid
id="testing"
url="google.com/test">
<!--In HEADER I used <table> tag because for some reasons (?) <tr>, <td> tags do not work without <table> tag.-->
<header>
<table><tr><td>One</td><td>Two</td><td>Three</td></tr></table>
</header>
<footer>
<p>footer</p>
</footer>
</datagrid>
指令JS
app.directive('datagrid', function(){
return {
restrict: 'EA',
scope: true,
transclude: true,
templateUrl: '../../datagrid.html',
link: function(scope, element, attr){
var header = element.find('header').html();
element.find('header').remove();
element.find('thead').html(header);
}
};
});
您可以为页脚编写相同的代码。
<强> datagrid.html 强>
<table class="datagrid table table-hover table-condensed table-striped">
<!-- Keep thead tag empty -->
<thead></thead>
<tbody>
<tr>
<!-- RESULTS -->
<td></td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
<div ng-transclude></div>
<!-- ng-transclude will include all custom html defined under <datagrid> directive -->
我希望这会对你有所帮助。
答案 1 :(得分:0)
我只需在指令的控制器中使用arg $ transclude。
// declaration of DataTable directive
.directive('datagrid', function () {
return {
restrict: 'E',
templateUrl: 'datagrid.htm',
scope: true,
transclude: true,
link: function ($scope, $el, $attr) {
var dtData = {
id: $attr.id,
url: $attr.url
};
if ($scope['datagrid'] === undefined) $scope['datagrid'] = [];
$scope['datagrid'].push([$attr.id, dtData]);
},
controller: function ($scope, $transclude) {
$transclude(function (clone, scope) {
console.log($(clone).find('header')); // don't work
$.each(clone, function (i, e) {
if ($(e).is('header')) console.log(e); //works
});
});
}
};
});
从此我相信我可以实现我的目标。只有仍然存在的问题,如果这是一个很好的方法,这会混淆我的插件的其他用户和为什么我不能用jQuery find方法选择“header”元素? :)
谢谢大家的帮助。希望我能很快完成其余的目标,这样我就可以在这里发布。完成它不应该有任何问题。