我有一个声明为Attribute的指令:
app.directive('myDirective', function() {
return {
restrict: 'A',
replace: true,
transclude: true,
scope: {
data: "="
},
template:
'<p class="my-paragrapgh">' +
'<label>Hello</label>' +
'</p>'
}
});
我有一个单元测试,但失败了:
describe('myDirective test', function () {
var scope, compile, element;
beforeEach(module('myModule'));
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
element = angular.element("<div my-directive></div>");
$compile(element);
scope.$digest();
}));
it('should have a my-paragrapgh class', function () {
expect($(element).find('p')[0]).toHaveClass('my-paragrapgh');
});
});
但是,如果我将求助对象转换为Element,并删除replace和transclude:
app.directive('myDirective', function() {
return {
restrict: 'E',
//replace: true,
//transclude: true,
scope: {
data: "="
},
template:
'<p class="my-paragrapgh">' +
'<label>Hello</label>' +
'</p>'
}
});
我的单元测试通过了:
describe('myDirective test', function () {
var scope, compile, element;
beforeEach(module('myModule'));
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
element = angular.element("<my-directive></my-directive>");
$compile(element);
scope.$digest();
}));
it('should have a my-paragrapgh class', function () {
expect($(element).find('p')[0]).toHaveClass('my-paragrapgh');
});
});
如何成功测试声明为属性的指令?我正在使用Karma,Jasmine和PhantomJS
ng-transclude
当您具有时,您将需要在模板中的某个位置,transclude: true
以便Angular知道将HTML注入的位置。尝试:
app.directive('myDirective', function() {
return {
restrict: 'A',
replace: true,
transclude: true,
scope: {
data: "="
},
template:
'<div ng-transclude><p class="my-paragrapgh">' +
'<label>Hello</label>' +
'</p></div>'
}
});
更新
看起来replace
这可能是导致此问题的选项。
app.directive('myDirective', function() {
return {
restrict: 'A',
scope: {
data: "="
},
template:
'<p class="my-paragrapgh">' +
'<label>Hello</label>' +
'</p>'
}
});
随着replace: true
您的内在HTML是:
失败
<label>Hello</label>
使用replace
undefined,您可以
经过
<p class="my-paragrapgh"><label>Hello</label></p>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句