我试图使用AngularJS(1.2)指令在HTML表格中创建行单元格,我不明白为什么Angular会将指令结果作为' body&#39的第一个孩子插入;而不是替换原始的指令元素?
以下是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
答案 0 :(得分:5)
如果你不将指令限制为一个元素,它似乎会更好:
app.directive('myDirective', function () {
return {
restrict: "A",
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);
}
};
});
<table>
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
</tr>
</thead>
<tbody>
<tr my-directive></tr>
</tbody>
</table>