以下是我的指令代码:
currentApp.directive('testList', ['$compile', function ($compile) {
return{
restrict: 'E',
template: '<table></table>',
replace: true,
compile: function (elem) {
return function ($scope, elem) {
var arr = ['Jay', 'John', 'David'];
angular.forEach(arr, function (val) {
elem.append('<tr><td>' + val + '</td></tr>');
});
$compile(elem)($scope);
}
}
}
}]);
这是我的测试代码:
describe('Tabletest', function () {
var element, scope, elem;
var linkingFn;
beforeEach(module('angularlearnApp'));
beforeEach(inject(function ($compile, $rootScope) {
scope = $rootScope;
elem = angular.element('<test-list></test-list> ');
linkingFn = $compile(elem);
element = linkingFn(scope);
}));
it('Testing table', function () {
console.info(element);
});
});
这是测试的输出:
Object{0: <table class="ng-scope">JayJohnDavid</table>, 1: , length: 2}
我很想知道为什么tr和td标签没有出现在这里,只出现了值。
答案 0 :(得分:0)
您需要.html()
而非.append()
,因为tr
是表格内容,并且您不会将它们附加到表格的末尾。 ;)
此外,您需要在将表格行传递到表格之前在循环中构建表格行,如果不是索引中的最新项目/名称,请继续替换之前的表格,并且您最终会使用表格只有一个表格行与大卫&#39;作为其内容。
currentApp.directive('testList', ['$compile', function ($compile) {
return {
restrict: 'E',
template: '<table/>',
replace: true,
link: function ($scope, elem) {
var arr = ['Jay', 'John', 'David'], trHTML ='';
angular.forEach(arr, function (val) {
trHTML += '<tr><td>' + val + '</td></tr>';
});
angular.element(elem).html(trHTML);
$compile(elem)($scope);
}
}
}]);
<强> JSFIDDLE 强>