Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

javascript - Setting view's name from decorator - Angular Ui Router

I'm defining my states in this way:

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

I want to write a 'decorator' for setting the view's name based on 'templateUrl' (As you see above, the view's name is empty).

This is the code for the 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;
});

Of course, this doesn't work. I'm a little bit lost.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a working plunker

You are almost there. Let's simplify a bit the state definition (because we do not need nested views object, we will create it later):

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

And this will be the decorator:

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

Check it here

Observe these as well:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...