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

时间:2014-09-25 08:46:05

标签: javascript jquery html angularjs iframe

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

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

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

iframe将包含其他独立应用。

iframe是要求

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

enter image description here

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

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

统一主应用窗口的路线和iframe路线的路线是否可行。

有什么想法吗?

1 个答案:

答案 0 :(得分:7)

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

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

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

在同一个母网页上,我还在需要时添加了iframe:)

<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');

显然这似乎是一种单向解决方案,除非我们还从子角应用程序创建向后网址修改,直到父窗口。

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

所以例如app1就是:

.run(["$rootScope", function ($rootScope) {

    $rootScope.$on('$routeChangeStart', function(next, current) {

    if (current.$$route){
        window.parent.location.hash = "#/app1" + current.$$route.originalPath;
    }

});
相关问题