0
votes

I'm trying to create a nested state config. When I go with the simple non-nested it works, but when I attempt to do it in a nested fashion it fails.

Below is the working code: (Notice the last state 'new')

app.config(
function($stateProvider, $urlRouterProvider) {

    $stateProvider
     .state('home', {
        url: '/home',
        templateUrl: '/views/home.html',
        controller: 'MainCtrl',
        resolve: {
            qstnrPromise: ['qstnrs', function(qstnrs) {
                return qstnrs.getAll();
            }]
        }
     })

     .state('questionnaires', {
        url: '/questionnaires/{id}',
        templateUrl: '/views/questionnaire.html',
        controller: 'QuestionsCtrl',
        resolve: {
            questionnaire: ['$stateParams', 'qstnrs', function($stateParams, qstnrs){
                return qstnrs.get($stateParams.id);
            }]
        }
     })

     .state('new', {
        url: '/questionnaires/{id}/new',
        template: '<h3> testy </h3>'
     });


     //$urlRouterProvider.otherwise('home');
     $urlRouterProvider.otherwise(function($injector, $location){
        $injector.invoke(['$state', function($state) {
            $state.go('home');
        }]);
     });
});

If I attempt to change it with the following, it fails. The URL on browser changes but I don't receive the template.

 .state('questionnaires.new', {
    url: '/new',
    template: '<h3>New question</h3>'
 });

Have I understood states incorrectly? Or where have I gone wrong?

2

2 Answers

0
votes

Try changing your new state to:

.state('new', {
  url: '/new',
  parent: 'questionnaires',
  template: '<h3>New question</h3>'
})

See if that works for you.

0
votes

You can make the questionnaires state abstract.

$stateProvider
.state('questionnaires', {
    abstract: true,
    url: '/questionnaires',
})
.state('questionnaires.new', {
    // url will become '/questionnaires/new'
    url: '/new'
    //...more
})

But in this case you will need to add one additional nested state in order to implement the functionality you need for the $stateParams.id.