angularjs ui-router:如何从状态 "parent" 过渡到 "parent.firstchild"?

angularjs ui-router: How to make a transition from state "parent" to "parent.firstchild"?

Parent 状态:

var roundsState = {
  name : 'rounds', 
  url: '/rounds',
  component: 'rounds',
  resolve : {
    rounds : function(RoundsService){
      return RoundsService.getRounds();
    }
  }
};

Child 状态:

var roundState = {
  name : 'rounds.round', 
  url: '/{roundUri}',
  component: 'round',
  resolve: {
    round: function(RoundsService, $transition$, $stateParams) {
      return RoundsService.getRound($transition$.params().roundUri);
    }
  }
};

正在尝试使用:

app.run(function($transitions) {
  $transitions.onSuccess({ to: 'rounds' }, function(trans) {
    return trans.router.stateService.go('rounds.round');
  });   
});

当成功转换到状态 "rounds" 时,我想转到状态 "rounds.round",但转到第一个 child。我正在阅读有关 grandchild 的内容,但我不明白。

请注意,我使用的是 ui-router 1.x

这里是plnkr上的实现示例: http://plnkr.co/edit/0C4aSB3a3fllYxa022Aq?p=preview

好吧,我将它与 $state 一起使用,它非常简单:

$state.go('rounds.round', {});

我认为你真的不应该使用 $transition$ 因为你真的不需要。

你可以这样写state.js:

angular.module('sampleApp')
    .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise(function ($injector) {
            var $state = $injector.get('$state');
            $state.go('home');
        });

        $stateProvider

            .state('parent', {
                abstract: true,
                templateUrl: 'views/parent/index.html'
            })

            .state('child', {
                parent: 'parent',
                abstract: true,
                url: '/child',
                template: '<ui-view/>'
            })

            .state('child.add', {
                url: '/add',
                templateUrl: 'views/child/add.html'
            });
}]);

然后在 HTML 中访问,如:

<a href="#" ui-sref="child.add"><span>Add Child</span></a>

您缺少 rounds.round 状态的 roundUri 参数。如果您看过控制台,您可能就知道了! :)

所以,我把它改成这样:

trans.router.stateService.go('rounds.round', {roundUri: "firstround"});

而且有效!

Working plunker

编辑

如何动态进入子状态?in ui-router v1.0

嗯,你可以在里面决定 $transitions.onSuccess。您可以注入某些依赖项并决定去哪里。像这样:

app.run(function($transitions, RoundsService) {
  $transitions.onSuccess({ to: 'rounds' }, function(trans) {
    RoundsService.getRounds().then(function(rounds) {
        return trans.router.stateService.go('rounds.round', {roundUri: rounds[0].uri});
    })
  });
});

请注意我是如何使用服务调用 RoundsService.getRounds() 来确定要访问哪个子 URI 的。

我已经修改了 rounds.json 以便其他一些状态(比如 roundof16)现在是第一个。而且,它会进入那个状态! :)

Updated plunker 用于动态子状态访问。