Angular Ui路由器多个命名视图和嵌套状态



当我在嵌套状态下使用多个命名视图时,我有一个关于Angular UI路由器的问题。基本上,我有一个抽象状态,其中有一个指向两个命名视图的模板。这两个命名视图都是在这两个子状态中定义的。我想将URL固定为/test。

当转换到任一子状态时,我只看到与第一个子状态相对应的视图。为什么?我真的希望有人能为我澄清这个概念,这样我就可以学习

JSFiddle在这里: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?
}]);

这实际上是定义它们的顺序。交换顺序,以便在test.sub1之前定义test.sub2,您会看到它将启动@test.sub2。

我认为这是因为没有为任何一个子状态分配url。我会尝试给他们自己的url路径,看看你是否可以这样引用这些州。

我的一位同事解释了这种情况下发生的情况。解释如下:

  1. state.transitionTo('test.subs2')导致应用程序进入状态'test.sub2'
  2. 一旦处于"test.subs2"状态,URL将更改为/test
  3. 这会导致Angular UI路由器触发对适当状态的更改
  4. 合适的状态是与URL/test匹配的第一个状态,即状态"test.subs1"

希望这能帮助

最新更新