Angular Ui router multiple named views and nested

2019-09-04 23:22发布

问题:

I have a question about the Angular UI router when I am using multiple named views in nested states. Basically I have an abstract state with a template that points to two named views. Those two named views are defined in both the sub states. I want to keep the URL fixed to /test.

When transitioning to either of the sub states, I see the view corresponding to the first sub state only. Why is that? I really hope someone can clarify the concept for me so I can learn

JSFiddle is here: https://jsfiddle.net/adeopura/e2c5n14o/16/

angular.module('myApp', ['ui.state'])
.config(['$stateProvider', '$routeProvider',  
function ($stateProvider, $routeProvider) {
    $stateProvider
        .state('test', {
            abstract: true,
            url: '/test',
            views: {
                'main': {
                     template:  '<h1>Hello!!!</h1>' +
                                '<div ui-view="view1"></div>' +
                                '<div ui-view="view2"></div>'
                }
            }
        })
        .state('test.subs1', {
            url: '',
            views: {
                'view1': {
                    template: "Im 1View1"
                },
                'view2': {
                    template: "Im 1View2"
                }
            }
        })
        .state('test.subs2', {
            url: '',
            views: {
                'view1': {
                    template: "Im 2View1"
                },
                'view2': {
                    template: "Im 2View2"
                }
            }
        });
}])
.run(['$rootScope', '$state', '$stateParams', function ($rootScope,   $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
    $state.transitionTo('test.subs1');//I see the data corresponding to the test.subs1
    // Assume here that there are lots of different state transitions in between unrelated to the test1 state
    $state.transitionTo('test.subs2');//I still see the data corresponding to the test.subs1, why is that?

}]);

回答1:

It's actually the order by which you've defined them. Swap the order so that you define test.sub2 before test.sub1 and you'll see it'll start @ test.sub2.



回答2:

I think it's because you don't have a url assigned to either of the sub-states. I would try giving them their own url paths, and seeing if you can then reference the states that way.



回答3:

One of my colleagues explained what is happening in this case. Explained as below:

  1. state.transitionTo('test.subs2') causes the application to go to state 'test.subs2'
  2. Once in state 'test.subs2', the URL is changed to /test
  3. This causes the Angular UI Router to fire a change to the appropriate state.
  4. The appropriate state is the first one that matches the URL /test, which would be the state 'test.subs1'

Hope this helps someone