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

时间:2015-10-13 21:26:11

标签: javascript angularjs angular-ui-router state angularjs-routing

我以这种方式定义我的状态:

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

当然,这不起作用。我有点失落。

1 个答案:

答案 0 :(得分: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['viewC@main'] = config;
      }
      else{
        result['viewB@main'] = config;
      }
    });

    return result;
  });

检查here

观察这些: