gpt4 book ai didi

angularjs - Angular 指令在 HTML 表格中无法正常工作

转载 作者:行者123 更新时间:2023-12-02 22:43:00 25 4
gpt4 key购买 nike

我正在尝试使用 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

最佳答案

如果不将指令限制为元素,似乎效果会更好:

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>

关于angularjs - Angular 指令在 HTML 表格中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25103334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com