3

我定義我的國家以這樣的方式設置視圖的從裝飾名字 - 角UI路由器

var parentStates = [ 
{state : 'home', url: '/home', template: 'home.html'}, 
{state : 'about', url: '/about', template: 'about.html'}, 
{state : 'contact', url: '/contact', template: 'contact.html'}, 
{state : 'home.data', url: '', template: 'data.html'}, 
{state : 'about.data', url: '', template: 'data.html'}, 
{state : 'contact.data', url: '', template: 'data.html'} 
]; 

$urlRouterProvider.otherwise("/main/home"); 

$stateProvider 
.state("main", { abtract: true, url:"/main", 
    views: { 
     "viewA": { 
      templateUrl:"main.html" 
     } 
    } 
}); 
parentStates.forEach(function(value){ 
    $stateProvider 
    .state("main." + value.state, { 
     url: value.url, 
     views: { 
      "": { 
       templateUrl: value.template 
      } 
     }, 
    }) 
}); 

我想寫一個'decorator'基於'templateUrl'設置視圖的名字(正如你看到的上面,該視圖的名稱爲空)

這是裝飾代碼:

$stateProvider.decorator('views', function (state, parent) { 
var result = {}, 
views = parent(state); 

// Don't touch the 'main state' 
if (state.name === "main") { 
    return views; 
} 

angular.forEach(views, function (config, name) { 
    if(config.templateUrl=='data.html'){ 
     result[name] = '[email protected]'; 
    } 
    else{ 
     result[name] = '[email protected]'; 
    } 
}); 
return result; 
}); 

當然,這是行不通的。我有點失落。

回答

1

a working plunker

你幾乎沒有。讓我們簡化了一下狀態定義(因爲我們不需要嵌套視圖對象,我們將在稍後創建它)

parentStates.forEach(function(value) { 
    $stateProvider 
     .state("main." + value.state, { 
     url: value.url, 
     templateUrl: value.template, 
     }) 
    }); 

,這將是裝飾:

$stateProvider.decorator('views', function(state, parent) { 
    var result = {}, 
     views = parent(state); 

    // some example when to not inject resolve 
    if (state.name === "main") { 
     return views; 
    } 

    angular.forEach(views, function(config, name) { 

     // the super child template 
     if(config.templateUrl === 'data.html'){ 
     result['[email protected]'] = config; 
     } 
     else{ 
     result['[email protected]'] = config; 
     } 
    }); 

    return result; 
    }); 

檢查它here

觀察這些還有:

+0

哇,太神奇了! Děkujimoc(: – robe007

+1

Maaaan;)這是驚人的;) –