从装饰器设置视图的名称 - Angular Ui 路由器

Setting view's name from decorator - Angular Ui Router

我是这样定义我的状态的:

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
            }
        },
    })
});

我想根据'templateUrl'写一个'decorator'来设置视图的名称(正如你在上面看到的,视图的名称是空的)

这是装饰器的代码:

$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] = 'viewC@main';
    }
    else{
        result[name] = 'viewB@main';
    }
 });
return result;
});

当然,这不行。我有点迷路了。

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['viewC@main'] = config;
      }
      else{
        result['viewB@main'] = config;
      }
    });

    return result;
  });

检查一下here

还要注意这些: