【发布时间】:2014-09-26 00:30:11
【问题描述】:
我正在尝试使用 AngularJS (1.2) 指令在 HTML 表格中创建行单元格,但我不明白为什么 Angular 将指令结果作为“body”的第一个子元素插入,而不是替换原始指令元素?
这是 HTML 标记:
<body ng-app="myApp" ng-controller="MainCtrl">
<table>
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
</tr>
</thead>
<tbody>
<my-directive></my-directive>
</tbody>
</table>
</body>
还有指令:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.data = ['value1','value2','value3','value4'];
});
app.directive('myDirective', function () {
return {
restrict: "E",
replace: true,
scope:false,
link: function (scope, element) {
var html = angular.element('<tr></tr>');
angular.forEach(scope.data, function(value, index) {
html.append('<td>'+value+'</td>');
});
element.replaceWith(html);
}
};
});
请使用下面的 Plunker 链接查看结果: http://plnkr.co/edit/zc00RIUHWNYW36lY5rgv?p=preview
【问题讨论】:
-
为了替换工作,使用模板。
-
我们不能总是使用模板属性(我的代码已经为示例进行了简化)。此外,replace 属性可以很好地与其他标签配合使用。我只是 html-table 的问题。
-
浏览器会自动丢弃表格中不正确或意外的标签。为了使您的指令有效,请将其用作属性而不是元素。
标签: angularjs html-table directive