2017-01-20 123 views
2

我有一個根狀態app它定義了主模板。我有一個需要用一個不同的特定路由交換這個模板:UI路由器。動態替換根狀態的模板

app.run(($rootScope, $state) => { 
    $rootScope.$on('$stateChangeStart', (toState, toParams, fromState, fromParams) => { 
    const rootState = $state.get('app'); 

    if (toState.name === 'app.new') { 
     rootState.template = require('../../new_layout.tpl.html'); 
    } else { 
     rootState.template = require('../../layout.tpl.html'); 
    } 
    } 
} 

此方法適用於初始應用負載,以及在應用程序狀態改變第一(但只能更改爲new_layout時)。當我試圖從app.new切換到某個其他狀態時,rootState's.template發生更改,但未應用(呈現)。

是否有合法的方式來動態替換根狀態的模板屬性?

回答

2

您可以使用ui-router查看目標來實現此目的。

$stateProvider.state({ 
    name: 'app', 
    url: '/app', 
    templateUrl: 'layout1.html', 
    }); 

    $stateProvider.state({ 
    name: 'app.new', 
    url: '/new', 
    views: { 
     // Target the unnamed ("") ui-view created in the root ("") 
     "@": { templateUrl: 'layout2.html' }, 
     // Target the unnamed ("") ui-view in the layout2 created by this state 
     "@app.new": { template: '<h1>app.new content</h1>' } 
    } 
    }); 

工作plunker:http://plnkr.co/edit/PmPn7kp1u1bRGeYeXK2H?p=preview

app.new(或任何子狀態)是有效的,它覆蓋用layout2.html根UI視圖的內容。然後它將自己的內容放入layout2.html的ui-view中。