3 回答

TA貢獻1777條經驗 獲得超10個贊
遵循Pavel的建議使用自定義指令,這是一個不需要在routeConfig中添加任何有效負載的版本,它是超級聲明性的,并且可以通過簡單地更改slice()您要注意的哪個路徑而適應于路徑的任何級別。
app.directive('detectActiveTab', function ($location) {
return {
link: function postLink(scope, element, attrs) {
scope.$on("$routeChangeSuccess", function (event, current, previous) {
/*
Designed for full re-usability at any path, any level, by using
data from attrs. Declare like this:
<li class="nav_tab">
<a href="#/home" detect-active-tab="1">HOME</a>
</li>
*/
// This var grabs the tab-level off the attribute, or defaults to 1
var pathLevel = attrs.detectActiveTab || 1,
// This var finds what the path is at the level specified
pathToCheck = $location.path().split('/')[pathLevel] ||
"current $location.path doesn't reach this level",
// This var finds grabs the same level of the href attribute
tabLink = attrs.href.split('/')[pathLevel] ||
"href doesn't include this level";
// Above, we use the logical 'or' operator to provide a default value
// in cases where 'undefined' would otherwise be returned.
// This prevents cases where undefined===undefined,
// possibly causing multiple tabs to be 'active'.
// now compare the two:
if (pathToCheck === tabLink) {
element.addClass("active");
}
else {
element.removeClass("active");
}
});
}
};
});
我們通過監聽$routeChangeSuccess事件來實現目標,而不是$watch在路徑上放一個。我的信念是,這意味著邏輯應該運行的頻率降低,因為我認為每個$digest周期都會觸發。
通過在指令聲明中傳遞路徑級別的參數來調用它。這指定要與href屬性匹配的當前$ location.path()中的哪個塊。
<li class="nav_tab"><a href="#/home" detect-active-tab="1">HOME</a></li>
因此,如果選項卡應對路徑的基本級別做出反應,則將參數設置為“ 1”。因此,當location.path()為“ / home”時,它將與中的“#/ home”相匹配href。如果您的選項卡應響應路徑的第二級,第三級或第十一級,請進行相應調整。從1或更大的切片將繞過href中邪惡的“?!保ㄎ挥谒饕?)。
唯一的要求是您在上調用<a>,因為該元素假定存在href屬性,該屬性將與當前路徑進行比較。但是,如果您喜歡在<li>或上進行調用,則可以輕松地進行調整以讀取/寫入父元素或子元素。我之所以這樣做,是因為您可以通過簡單地更改pathLevel參數在許多情況下重用它。如果邏輯中假定要讀取的深度,則您需要該指令的多個版本才能與導航的多個部分一起使用。
編輯3/18/14:解決方案的推廣不充分,如果您定義了undefined針對同時針對$location.path()和元素的返回的'activeTab'值的arg,則該解決方案將被激活href。因為:undefined === undefined。已更新以解決該問題。
在進行此操作時,我意識到應該有一個可以在父元素上聲明的版本,其模板結構如下:
<nav id="header_tabs" find-active-tab="1">
<a href="#/home" class="nav_tab">HOME</a>
<a href="#/finance" class="nav_tab">Finance</a>
<a href="#/hr" class="nav_tab">Human Resources</a>
<a href="#/quarterly" class="nav_tab">Quarterly</a>
</nav>
請注意,此版本不再與Bootstrap樣式的HTML相似。但是,它更現代,使用的元素更少,所以我偏愛它?,F在,該版本的指令以及原始指令可以在Github上作為嵌入式模塊使用,您可以將其聲明為依賴項。如果有人真正使用它們,我很樂意對其進行Bower化處理。
另外,如果您想要一個包含<li>的兼容引導程序的版本,則可以使用 angular-ui-bootstrap Tabs模塊,我認為它是在本原始帖子之后發布的,它可能比本聲明更具聲明性。對于基本內容而言,它不夠簡潔,但是為您提供了一些其他選項,例如禁用的選項卡以及在激活和停用時觸發的聲明性事件。
添加回答
舉報