In Angular ui-router child template not working

2019-06-17 07:10发布

问题:

I have registered a state test with a child .child1 , here parent (test) working fine . when i navigate to state test.child1 URL gets changed to #/test/child1 but the view remains same , child template not working

angular.module('uiRouterSample.contacts', [
  'ui.router'
])

.config(
  [          '$stateProvider', '$urlRouterProvider',
    function ($stateProvider,   $urlRouterProvider) {
      $stateProvider
      .state('test',{
            url:'/test',            
            template:'<a ui-sref="test">Parent</a> -> <a ui-sref=".child1">child1</a>',
            controller: ['$scope', '$state', 'contacts', 'utils',
              function (  $scope,   $state,   contacts,   utils) {
              }]
        }).state('test.child1',{
            url:'/child1',            
            template:'Child template working fine'
        })
    }
  ]
)        

回答1:

You need a ui-view directive in the template of the parent state (the test state):

  template:'<div ui-view/> <a ui-sref="test">Parent</a>  <a ui-sref=".child1">child1</a></div>',

Basically whenever you have a state in ui-router which will have child states, the immediate parent pf that child state must also have a ui-view directive in its template.



回答2:

Posting this as answer as I do not have enough reps to comment. As mentioned by Mohammad, you need a ui-view inside the template of the parent state. The ui-view in your Index html only allows you to render the parent state(test state), but in order for .child1 state to be rendered, it needs another ui-view inside its parent state, which in this case is the test state.

Thus, configure your test state's template to contain a ui-view:

angular.module('uiRouterSample.contacts', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider',
   function ($stateProvider,   $urlRouterProvider) {
     $stateProvider
       .state('test',{
         url:'/test',            
         template:'<div ui-view/> <a ui-sref="test">Parent</a> -> <a ui-sref=".child1">child1</a></div>',
         controller: ['$scope', '$state', 'contacts', 'utils',
           function (  $scope,   $state,   contacts,   utils) {
           }]})
    .state('test.child1',{
        url:'/child1',            
        template:'Child template working fine'
    })
   }]