rav*_*shi 30 html javascript angularjs angularjs-directive angularjs-ng-repeat
我正试图在多个地方重用我的HTML视图的一部分.我想重用的部分是HTML表格中的表格单元格.问题是我在ng-repeat中的自定义指令正在做有趣的事情.我在jsFiddle上重现了这个问题.jsFiddle中有两个HTML表.第一个是ng-repeat,表格单元格写在视图中,第二个是来自指令my-element的表格单元格.Chrome开发工具报告呈现的HTML看起来像这样.请注意,自定义元素只出现一次,位于表格之外.
呈现HTML
<div ng-controller="MyCtrl" class="ng-scope">
table1
<table class="table table-hover">
<tbody><!-- ngRepeat: p in people -->
<tr ng-repeat="p in people" class="ng-scope">
<td class="ng-binding">Name: Mike</td>
<td class="ng-binding">Age: 20</td>
</tr>
<tr ng-repeat="p in people" class="ng-scope">
<td class="ng-binding">Name: Peter S</td>
<td class="ng-binding">Age: 22</td>
</tr>
</tbody>
</table>
<br>table2
<my-element class="ng-binding">Name: Age: </my-element>
<table class="table table-hover">
<tbody>
<!-- ngRepeat: p in people -->
<tr ng-repeat="p in people" class="ng-scope">
</tr>
<tr ng-repeat="p in people" class="ng-scope">
</tr>
</tbody>
</table>
</div>
Run Code Online (Sandbox Code Playgroud)
来源HTML
<div ng-controller="MyCtrl">
table1
<table class="table table-hover">
<tr ng-repeat="p in people">
<td>Name: {{ p.name }}</td>
<td>Age: {{ p.age }}</td>
</tr>
</table>
<br/>table2
<table class="table table-hover">
<tr ng-repeat="p in people">
<my-element></my-element>
</tr>
</table>
</div>
Run Code Online (Sandbox Code Playgroud)
来源JS
var app = angular.module('myApp', []);
app.directive('myElement', function () {
return {
restrict: 'E',
template: '<td>Name: {{ p.name }}</td><td>Age: {{ p.age }}</td>'
}
});
function MyCtrl($scope) {
$scope.people = [{
name: 'Mike',
age: 20
}, {
name: 'Peter S',
age: 22
}];
}
Run Code Online (Sandbox Code Playgroud)
请注意,jsFiddle是一个简单的例子,常识会导致根本不使用指令.但是,我的目标代码有一个更大的模板,我想重复使用.我也试过使用"ng-include",结果也差不多.
m59*_*m59 59
<td>
众所周知,在这样的指令中表现得很奇怪.相反,在父级上使用指令<tr>
.在这里阅读有关此问题的更多信息:https://github.com/angular/angular.js/issues/1459
<table>
<tr ng-repeat="p in people" my-element></tr>
</table>
Run Code Online (Sandbox Code Playgroud)
以下是如何进一步改进指令以使其更易于重复使用的方法.
app.directive('myElement', function () {
return {
scope: {
item: '=myElement'
},
restrict: 'EA',
template: '<td>Name: {{item.name}}</td><td>Age: {{item.age}}</td>'
};
});
Run Code Online (Sandbox Code Playgroud)
并传递item
像这样的值:
<table>
<tr ng-repeat="person in people" my-element="person"></tr>
</table>
Run Code Online (Sandbox Code Playgroud)
zs2*_*020 13
将指令应用于<tr>
此:
<table class="table table-hover">
<tr my-element blah='p' ng-repeat="p in people"></tr>
</table>
app.directive('myElement', function () {
return {
restrict: 'A',
scope:{
ngModel: '=blah'
},
template: '<td>Name: {{ ngModel.name }}</td><td>Age: {{ ngModel.age }}</td>'
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
46214 次 |
最近记录: |