我正在尝试测试指令的UI状态,该指令通过ng-include动态加载模板。我遇到了元素未定义的问题,在谷歌搜索后,修复是简单地将编译后的元素与父html元素(即div)包装在一起。这解决了未定义元素的问题,但是现在该元素被定义为注释节点,而不是呈现的模板。
指令
function myDirective(
return {
scope: {
tpl: '@'
},
template: '<ng-include src="template"/>',
link: function(scope, elem, attr, ctrl) {
if(scope.tpl == 'view') {
scope.template = 'app/view.tpl.html';
}
if(scope.tpl == 'edit') {
scope.template = 'app/edit.tpl.html';
}
指令的父模板
<my-directive ng-repeat="item in vm.myStuff track by $index" tpl="edit">
</my-directive>
规格
describe('myDirective', function() {
var $rootScope, $compile, element, scope;
beforeEach(inject(function($injector) {
$rootScope = $injector.get("$rootScope");
$httpBackend = $injector.get("$httpBackend");
$compile = $injector.get("$compile");
element = angular.element('<div><my-directive ng-repeat="item in vm.myStuff track by $index" tpl="edit"></my-directive></div>');
scope = $rootScope.$new();
// wrap scope changes using $apply
scope.$apply(function() {
scope.template = 'app/edit.tpl.html';
scope.vm = {
myStuff: [{}, {}]
};
$compile(element)(scope);
});
}));
it("edit template save button should be displayed", function() {
console.log(element.html());
'<!-- ngRepeat: item in vm.myStuff track by $index -->'
});
});
添加myStuff数组后输出
<div>
<!-- ngRepeat: item in vm.myStuff track by $index -->
<!-- ngIf: !$last && item -->
<my-directive ng-repeat="item in vm.myStuff track by $index" tpl="edit">
</my-directive>
<!-- end ngIf: !$last && widget -->
<!-- end ngRepeat: item in vm.myStuff track by $index -->
<!-- ngIf: !$last && item -->
<!-- end ngRepeat: item in vm.myStuff track by $index -->
</div>
我添加了ng-repeat
的数据,但是现在看到注释的指令,但是看不到呈现的edit.tpl.html
模板。
答案 0 :(得分:0)
ng-repeat
指令需要数据:
beforeEach(inject(function($injector) {
$rootScope = $injector.get("$rootScope");
$httpBackend = $injector.get("$httpBackend");
$compile = $injector.get("$compile");
element = angular.element('<div><my-directive ng-repeat="item in vm.myStuff track by $index" tpl="edit"></my-directive></div>');
scope = $rootScope.$new();
// wrap scope changes using $apply
scope.$apply(function() {
//INIT vm.myStuff
scope.vm = {myStuff: ["item1"]};
//
scope.template = 'app/edit.tpl.html';
$compile(element)(scope);
});
}));
ng-repeat="item in vm.myStuff
指令将元素转换为注释节点。仅在有数据时才添加元素。