ui-router nested states, basic understanding

时间:2016-10-19 13:35:33

标签: angularjs angular-ui-router

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 个答案:

答案 0 :(得分:0)

尝试将新状态更改为:

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

看看它是否适合你。

答案 1 :(得分:0)

您可以将调查问卷说明为抽象

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

但在这种情况下,您需要添加一个额外的嵌套状态,以实现 $ stateParams.id 所需的功能。