angularjs - Can I manage dynamic controllers based on $stateParams? -
i'm working ui-router. know of set dynamic templateurl i'd manage dynamic controller.
here i'm looking for:
$stateprovider.state('town.building', { url: "/building?id", templateurl: function ($stateparams) { // working dynamic templateurl if ($stateparams.hasownproperty('id')) { switch (number($stateparams.id)) { case 1: return "views/factory.html"; /* case 2, case 3, etc. */ default: return null; } } return null; }, controller: function ($stateparams) { // dynamic controller ? if ($stateparams.hasownproperty('id')) { switch (number($stateparams.id)) { case 1: return "myfirstcontroller"; /* case 2, case 3, etc. */ default: return "defaultcontroller"; } } return null; } });
is possible ? going wrong way ?
this do:
$stateprovider .state('intermediary-state', { url: '/', onenter: ['$stateparams', '$state', function ($stateparams, $state) { if ($stateparams.id === '1') { $state.go('somewhere'); } else { $state.go('somewhere-else'); } }] }) .state('somewhere', { url: '/somewhere', controller: 'somewherectrl' }) .state('somewhere-else', { url: '/somewhere-else', controller: 'somewhereelsectrl' });
the logic behind i'm using intermediary state grabs stateparams, evaluates , redirects accordingly.
this being said, i'm not sure why need controllers dynamic based on stateparams. seems code smell me well, , better option depend on underlying service.
for example might have different "home" state/controller logged in user versus guest user, , authenticationservice responsible of logic.
$stateprovider .state('intermediary-state', { url: '/', onenter: ['authenticationservice', '$state', function (authenticationservice, $state) { if (authenticationservice.isloggedin()) { $state.go('home-user'); } else { $state.go('home-guest'); } }] })
Comments
Post a Comment