首页 文章

统一路由URL以获取在iframe内呈现的独立页面

提问于
浏览
11

我在angularjs上有很少的应用程序(单页面应用程序,独立) . 它们具有不同的UI样式 .

我不得不在页面左侧创建带有导航面板的新应用程序(独立),并在页面右侧创建iframe .

导航面板部分解决了UI样式统一问题 .

iframe将包含其他独立应用 .

iframe是 requirment

我已经使用navigationJs创建了带导航和iframe的主应用程序 .

enter image description here

因此,主应用程序通过iframe加载独立模块(SPA / AngularJs),这些模块工作正常 .

但是,存在一个“小”问题 . 每个独立模块都有自己的angularjs路由 . 它可以工作,但不会显示在主窗口中(在iframe所在的主应用程序中)

是否可以统一主应用程序窗口的路径和iframe路径的路径 .

有任何想法吗?

1 回答

  • 7

    好的,我花了一点时间为您提出一个有效的解决方案 . 然而,它预先假定一定程度的一致性和对角度应用的控制 .

    第一步是简单地添加导航,其链接指向我的子角度应用程序的部分:

    <nav>
        <ul>
            <li><a href="#/app1/main">App1</a></li>
            <li><a href="#/app2/home">App2</a></li>
        </ul>
    </nav>
    

    在同一个父页面上,我还添加了一个iframe require :)

    <section>
        <iframe src=""></iframe>
    </section>
    

    使用以下脚本来处理父窗口中的地址更改:

    // Simple method to look for the second index of something
    String.prototype.secondIndexOf = function (val) {
        var fst = this.indexOf(val);
        var snd = this.indexOf(val, fst + 1)
        return snd
    }
    
    // My goto method to basically go to somewhere in my angular apps
    function goto(app, route) {
        $('iframe').attr('src', app + '/test.html#' + route)
    }
    
    // upon hash change of the parent page I will call my goto method if there is a hash
    $(window).on('hashchange', function () {
        var hash = location.hash;
    
        if (hash) {
            var appName = hash.substring(hash.indexOf('app'), hash.indexOf('app') + 4);
            var route = hash.substring(hash.secondIndexOf('/'));
            goto(appName, route);
        }
    
    });
    
    // On initial page load I also like to trigger this hash change to
    // go to the right location initially
    $(window).trigger('hashchange');
    

    显然,这似乎是单向解决方案,除非我们还创建从子角度应用程序返回到父窗口的向后URL修改 .

    为了实现这一点,我决定将哈希更改重新推送到每个应用程序的$ routeChangeStart事件中的父窗口:

    所以例如对于app1它将是:

    .run(["$rootScope", function ($rootScope) {
    
        $rootScope.$on('$routeChangeStart', function(next, current) {
    
        if (current.$$route){
            window.parent.location.hash = "#/app1" + current.$$route.originalPath;
        }
    
    });
    

相关问题