[英]angular-ui-router shares state between multiple tabs in browser
[英]angular-ui-router and angular-ui-bootstrap tabs: content being loaded into DOM multiple times
我正在使用angular-ui-bootstrap 選項卡和angular-ui-router。 單擊選項卡時,我想將特定狀態加載到選項卡窗格中。 一切正常。 問題在於狀態被加載到DOM中的每個選項卡窗格中。 盡管用戶永遠不會說,但是讓所有這些內容在DOM中不必要地重復並不是一個好主意。 發生這種情況的原因很明顯-狀態模板已插入到ui-view中,如下所示:
<tabset>
<tab class="clinical-tabs" ng-repeat="tab in tabs" heading="{{tab.title}}" active="tab.active" disabled="tab.disabled" ui-sref="activity.clinical.{{tab.title}}">
<div ui-view></div>
</tab>
</tabset>
結果是在每個選項卡窗格中都加載了內容:
<div class="tab-content">
<!-- ngRepeat: tab in tabs -->
<div class="tab-pane ng-scope active" ng-repeat="tab in tabs" ng-class="{active: tab.active}" tab-content-transclude="tab">
<!-- uiView: -->
<div ui-view="" class="ng-scope">
CONTENT IS LOADED HERE
</div>
</div>
<!-- end ngRepeat: tab in tabs -->
<div class="tab-pane ng-scope" ng-repeat="tab in tabs" ng-class="{active: tab.active}" tab-content-transclude="tab">
<!-- uiView: -->
<div ui-view="" class="ng-scope">
CONTENT IS ALSO LOADED HERE
</div>
</div>
<!-- end ngRepeat: tab in tabs -->
...
...
...
</div>
就像我說的那樣,問題的原因很明顯。 但是,我對Angular的經驗不足,無法知道如何提出解決方案。
雖然我對這個tab指令不熟悉,但是如果您只希望將內容加載一次,則可以使用ngRepeat
的$first
特殊作用域變量,該變量僅在第一次迭代時才等於true
。
將其與ngIf
結合使用,您將獲得以下內容:
<tabset>
<tab class="clinical-tabs" ng-repeat="tab in tabs" heading="{{tab.title}}" active="tab.active" disabled="tab.disabled" ui-sref="activity.clinical.{{tab.title}}">
<div ng-if="$first" ui-view></div>
</tab>
</tabset>
會產生:
<div class="tab-content">
<!-- ngRepeat: tab in tabs -->
<div class="tab-pane ng-scope active" ng-repeat="tab in tabs" ng-class="{active: tab.active}" tab-content-transclude="tab">
<!-- uiView: -->
<div ui-view="" class="ng-scope">
CONTENT IS LOADED HERE
</div>
</div>
<!-- end ngRepeat: tab in tabs -->
<div class="tab-pane ng-scope" ng-repeat="tab in tabs" ng-class="{active: tab.active}" tab-content-transclude="tab">
</div>
<!-- end ngRepeat: tab in tabs -->
...
...
...
</div>
我找到了解決方案。 訣竅是在ui-router中使用多個命名視圖
應當更改HTML代碼,以便現在命名ui視圖(注意,不再需要ui-sref):
<tabset>
<tab class="clinical-tabs" ng-repeat="tab in tabs" heading="{{tab.title}}" active="tab.active">
<div ui-view="{{tab.title}}"></div>
</tab>
</tabset>
在主模塊中,$ stateProvider應配置不同有一個很好的教程與UI的路由器設置了多個命名視圖這里 。 結構應類似於:
.state('[parent]', {
url: '/[someurl]',
views: {
'': { //<--this is the main template
templateUrl: 'views/[view].html',
controller: '[controller]'
},
'[child]@[parent]': { //<--these are the nested, named views that correspond to each tab
templateUrl: 'views/[view].html',
controller: '[controller]'
},
'...
現在,不是將一個模板注入DOM 5次(用於5個選項卡),而是將每個模板注入其正確的ui視圖中,因此沒有重復項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.