rpa*_*che 4 html-table directive angularjs
我正在尝试使用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>
Run Code Online (Sandbox Code Playgroud)
指令:
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);
}
};
});
Run Code Online (Sandbox Code Playgroud)
请使用下面的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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
954 次 |
| 最近记录: |