我有一个Angular指令,它通过检测打开模态的组件外部的点击来关闭模态窗口:
module showmodal {
'use strict';
export class ShowModal implements ng.IDirective {
restrict: string = 'A';
scope: any = {
showModal: '=showModal'
};
link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes) => {
function handler(): void {
if ((element[0] !== event.target) && (0 === element.find(event.target).length)) {
scope.$apply((): void => {
scope['showModal'] = false;
});
}
}
this.$document.on('click', handler);
scope.$on('$destroy', () => {
this.$document.off('click', handler);
});
};
constructor(
private $document: ng.IDocumentService,
private $parse: ng.IParseService) {
}
static instance(): ng.IDirectiveFactory {
const factory: ng.IDirectiveFactory = (
$document: ng.IDocumentService,
$parse: ng.IParseService): ng.IDirective => {
return new ShowModal($document, $parse);
};
factory.$inject = [
'$document',
'$parse'
];
return factory;
}
}
angular.module('showmodal')
.directive('showModal', ShowModal.instance());
}
实施为:
<div ng-init="showModal=false" show-modal="showModal">
<input type="text" class="input" ng-click="showModal=!showModal" />
<div class="modal" ng-show="showModal">The modal</div>
</div>
代码按预期工作 . 用户单击将showModal设置为true的输入,显示模态,当他们单击页面上的任何其他位置时,指令检测到单击,确定是否在元素外部触发,如果是,则将showModal设置为false,隐藏模态 .
我试图测试该指令 . 点击事件不会从Jasmine测试中被触发 . 这是我到目前为止:
module showmodal {
'use strict';
var element: ng.IAugmentedJQuery;
var scope: any;
describe('ShowModal directive', () => {
beforeEach(() => {
angular.mock.module('showmodal');
angular.mock.inject(($rootScope: ng.IRootScopeService, $compile: ng.ICompileService) => {
scope = $rootScope.$new();
var html: ng.IAugmentedJQuery =
angular.element('<div class="click" ng-click=""></div><div ng-init="showModal=false" show-modal="showModal"><input type="text" class="input" ng-click="showModal=!showModal" /><div class="modal" ng-show="showModal">The modal</div></div>');
element = $compile(html)(scope);
scope.$apply();
});
});
iit('should set showModal to false', () => {
expect(scope.showModal).toBeFalsy();
element.find('.input').triggerHandler('click');
scope.$apply();
expect(scope.showModal).toBeTruthy();
element.find('.click').triggerHandler('click'); <- element is clicked but does not fire the click event in the directive.
scope.$apply();
expect(scope.showModal).toBeFalsy(); <- fails here
});
});
}
理论上,测试单击将showModal设置为true的输入(这是有效的) . 然后它点击带有'click'类的div,它应该触发指令中的click事件,但它不会 .
1 回答
我通过创建一个单击$ document而不是单击div来解决这个问题: