简体   繁体   English

AngularJS + Bootstrap记得活动标签

[英]AngularJS + Bootstrap remember active tab

I've developed a simple AngularJS app that utilizes the Bootstrap directive. 我开发了一个使用Bootstrap指令的简单AngularJS应用程序。 Several of my pages uses tabs. 我的几个页面都使用了标签。 The problem is, when im in a tab (other than the first one) and presses a link that leads to another view and go back (back button in browser or application) from that view, the previously active tab isn't the active anymore. 问题是,当我在一个标签(不是第一个)中按下一个链接导致另一个视图并从该视图返回(浏览器或应用程序中的后退按钮)时,之前活动的标签不再是活动标签了。

I guess that Angular somehow uses pushState or something like that to keep track of the previous pages, since the length property of window.history is increased when im navigating within the app. 我猜Angular以某种方式使用pushState或类似的东西来跟踪前面的页面,因为当我在应用程序中导航时, window.history的length属性会增加。 Could i somehow attach extra data to the state which contains information about the active tab? 我可以以某种方式将额外数据附加到包含有效选项卡信息的状态吗?

I've tried using pushState to append a tab parameter to the URL. 我已经尝试使用pushState将一个tab参数附加到URL。 First time pushState is called it works fine. 第一次调用pushState它工作正常。 However, the second time Angular goes into some kind of loop causing the page to crash (eventually). 然而,第二次Angular进入某种循环导致页面崩溃(最终)。 How should i implement this? 我应该如何实现这个?

After looking at a combination of several solutions (assist from here: http://bit.ly/1qIemCh ) and condensing it down to a working solution, this was the one that allowed AngularJS + Bootstrap Tabs for me. 在查看了几个解决方案的组合(从这里得到帮助: http//bit.ly/1qIemCh )并将其缩小为工作解决方案之后,这就是允许我使用AngularJS + Bootstrap Tabs解决方案。 The trick is to leverage the HTML5 pushstate to grab the URL hash from history in JS, find the applicable tab, and show it. 诀窍是利用HTML5 pushstate从JS中的历史记录中获取URL哈希,找到适用的选项卡并显示它。

Tabs: 标签:

<ul class="nav nav-tabs" role="tablist" id="myTab">
    <li class="active"><a href="#" data-target="#">Home</a></li>
    <li><a href="#/tab2" data-target="#">Tab 2</a></li>
    <li><a href="#/tab3" data-target="#">Tab 3</a></li>
</ul>

This JS will activate the proper tab from history or if being navigated too via a bookmark : 这个JS将从历史记录中激活正确的选项卡,或者通过书签进行导航:

function setActiveTab() {
    var hash = window.location.hash;

    var activeTab = $('.nav-tabs a[href="' + hash + '"]');
    if (activeTab.length) {
        activeTab.tab('show');
    } else {
        $('.nav-tabs a:first').tab('show');
    }
};

//If a bookmark was used to a particular page, make sure to 
//activate the correct tab after initial load:
$(document).ready(function() {
    setActiveTab();
});

//When history.pushState() activates the popstate event, switch to the currently
//selected tab aligning with the page being navigated to from history.
$(window).on('popstate', function () {
    setActiveTab();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM