没有URL的状态的AngularJS ui-router默认状态

F L*_*has 3 javascript angularjs angular-ui-router

我们在一个页面上有几种状态,因此状态没有分配任何URL.有没有办法为无URL状态指定默认状态?也许类似于$urlRouterProvider.otherwise('/');.

我尝试在Angular的run语句中或在控制器内进入状态,但这会导致transition superseded错误,这可能是由于$state尚未初始化的事实.

以下是一个简短的例子.我想直接开始stateA.

angular
  .module('myModule')
  .config([
    '$stateProvider',
    function($stateProvider) {
      $stateProvider
        .state('stateA', {
          controller: function () {
            // Do some magic related to state A
          }
        })
        .state('stateB', {
          controller: function () {
            // Do some magic related to state B
          }
        });
    }
  ])
  .controller(['$state', '$timeout', function($state, $timeout){
    // My global controller
    // To set a default state I could do:
    // $timout(function () {
    //   $state.go('stateA'); 
    // }, 0);
    // But that doesn't feel right to me.
  }]);
Run Code Online (Sandbox Code Playgroud)

更新:由于这个答案,我想出了我必须包装$state.go成一个$timeout,以避免transition superseded错误.

小智 5

这将调用一个自定义规则,该规则进入默认状态而不会篡改URL.

$urlRouterProvider.otherwise(function($injector) {
    var $state = $injector.get('$state');
    $state.go('stateA');
});`
Run Code Online (Sandbox Code Playgroud)