我可以使用 ui-router 作为索引的子状态吗?

Can I have a child state that is the index using ui-router?

我的路线如下:

$stateProvider.state('repository', {
  url: '/:host/:owner/:repository',
  views: {
    appView: {
      templateUrl: '/templates/app/repository.html'
    }
  }
}).state('repository.analytics', {
  views: {
    repositoryView: {
      templateUrl: '/templates/app/_repositoryAnalytics.html'
    }
  }
}).state('repository.commit', {
  url: '/:host/:owner/:repository/commit/:commitHash',
  views: {
    repositoryView: {
      templateUrl: '/templates/app/_repositoryCommit.html'
    }
  }
}).state('repository.file', {
  url: '/file?path',
  views: {
    repositoryView: {
      templateUrl: '/templates/app/_repositoryFile.html'
    }
  }
});

我想要所有类似 repository 的状态的基础 URL,这就是为什么我在那里指定 url。例如,如果我不这样做,我将不得不指定在 commit 状态中显示的所有内容。这很冗长,不是我想做的。

那么是否可以为 repository 设置一个 default 子状态,这样如果有人被定向到那里,那么该子视图就会加载?

** 更新 ** 如果我点击应用程序,这似乎工作得很好,但如果我直接转到 /:host/:owner/:repository URL,子视图(分析)永远不会加载。

我不知道你是否可以有一个默认的子状态,但你可以在该父状态中设置子视图。像这样:

$stateProvider.state('repository', {
  url: '/:host/:owner/:repository',
    views: {
      appView: {
        templateUrl: '/templates/app/repository.html'
      },
      'repositoryView@repository': { // it means the repositoryView of repository state.
        templateUrl: '/templates/app/_repositoryAnalytics.html'    
      }
    }
  })

然后,当您使用存储库状态或 URL 打开时,分析页面将加载到存储库页面的 repositoryView 视图中。

[更新] 此格式 'repositoryView@repository' 表示视图 'repositoryView' 处于状态 'repository'。因为你尝试用默认的子视图打开状态'repository'。子视图 'repositoryView' 定义在 'repository.html' 中。如果你没有设置状态范围,ui-router 会认为子视图 'repositoryView' 属于 'repository' 的父视图。

不知道我解释清楚没有,你可以看看ui-router wiki

我创建了 working plunker here。一种方法是使用事件强制 进入 child 状态,当 parent 被选择时 (从url)

.run(['$rootScope', '$state', '$stateParams',
  function($rootScope, $state, $stateParams) {

    $rootScope.$on('$stateChangeStart', function(event, toState, toPrams) {
      if (toState.name === "repository") {
        event.preventDefault();
        $state.go('repository.analytics', toPrams);
      }
    });
  }
])

检查一下here

关于父子重定向的一些其他主题:

  • Angular UI-Router $urlRouterProvider .when not working when I click <a ui-sref="...">
  • Angular UI-Router $urlRouterProvider .when not working *anymore*