当您的 Angular 应用程序在 DOM 就绪时,Angular 场景会很好地工作。使用 requirejs 或其他 AMD 库时情况并非如此。如何在 Angular 场景中添加对 AMD 的支持?
最佳答案
您需要做的是覆盖默认的框架加载行为,并在您的应用准备就绪时发出新事件。
第一件事是在您的 Angular 应用程序中添加以下行以及 angular.bootstrap 调用。 Angular 场景需要此数据。
angular.bootstrap(document, ['app']);
var html = document.getElementsByTagName('html')[0];
html.setAttribute('ng-app', 'app');
html.dataset.ngApp = 'app';
if (top !== window) {
top.postMessage({
type: 'loadamd'
}, '*');
}
接下来,在您的 e2e 运行程序中,您必须包含这些行。如果是外部脚本,则必须在 angular-scenario 之后加载,并且必须在 DOM 准备好之前解析:
/**
* Hack to support amd with angular-scenario
*/
(function() {
var setUpAndRun = angular.scenario.setUpAndRun;
angular.scenario.setUpAndRun = function(config) {
if (config.useamd) {
amdSupport();
}
return setUpAndRun.apply(this, arguments);
};
function amdSupport() {
var getFrame_ = angular.scenario.Application.prototype.getFrame_;
/**
* This function should be added to angular-scenario to support amd. It overrides the load behavior to wait from
* the inner amd frame to be ready.
*/
angular.scenario.Application.prototype.getFrame_ = function() {
var frame = getFrame_.apply(this, arguments);
var load = frame.load;
frame.load = function(fn) {
if (typeof fn === 'function') {
angular.element(window).bind('message', function(e) {
if (e.data && e.source === frame.prop('contentWindow') && e.data.type === 'loadamd') {
fn.call(frame, e);
}
});
return this;
}
return load.apply(this, arguments);
}
return frame;
};
}
})();
最后,要启用 amd 配置,您必须将属性 ng-useamd 添加到 angular-scenario 的脚本标签中。
<script type="text/javascript" src="lib/angular-1.0.3/angular-scenario.js" ng-autotest ng-useamd></script>
你现在准备好了
已使用 angular-scenario v1.0.3 进行测试
关于javascript - 如何在 requirejs 中使用 Angular 场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15499997/