3

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.

1 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, amazing ! Děkuji moc (:
Maaaan ;) that is amazing ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.