javascript - 如何在 requirejs 中使用 Angular 场景

标签 javascript angularjs requirejs angular-scenario

当您的 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/

相关文章:

javascript - 检测覆盖 iframe 的系统窗口

javascript - Safari 11 对 HTML5 音频的新自动播放限制

javascript - Angularjs 在节点 webkit 应用程序中将图像 src 更改为 “unsafe:”

javascript - 无法在 Angular 中使用 Javascript 将光标聚焦

javascript - 如何在 4 个文件上禁用 AMD 并使用 webpack 按顺序加载它们

javascript - 如何使用数据库值设置谷歌地图标记

javascript - 如何使用 jQuery 获取点击的 div 的 CSS?

javascript - TypeError : customerFactory. getOrders 不是函数

requirejs - 如何在 require.js 中使用hammer.js 插件

asp.net-mvc - 如何使用RequiresJs加载typescript模块(asp.net mvc/visual studio环境)