【问题标题】:AngularJS: How to have default nested state using UI Router?AngularJS:如何使用 UI 路由器获得默认嵌套状态?
【发布时间】:2015-01-27 09:39:24
【问题描述】:

我目前有一个带有单个 ui-view 的根 index.html,它会根据用户所在的“页面”被替换,例如书籍、游戏等。以书籍页面为例,此视图包含我希望在属于“书籍”空间的所有页面上显示的内容,但中心内容会根据用户是否打开而有所不同书籍“主页”或查看特定书籍。为此,我的 books.html 有一个嵌套状态,其中包括 books_list.html 或 books_detail.html。

我想要的 url 结构是:

  • /books - 显示左侧/右侧面板以及页面中间的书籍列表。
  • /books/1 - 在页面中间显示左侧/右侧面板以及 ID 为 1 的书籍的详细信息(不显示书籍列表)。

如何设置我的状态,以便在导航到 /books 时在嵌套视图中有 books.html 模板和 books_list.html 模板,但在导航到 /books/1 时有 books.html 和 books_detail.html?

我目前正在通过有一个“家”子状态来解决这个问题,但这意味着我必须有 /books/home,并且 /books 不显示中心内容,因此目前没有用。

.state('books', {
    url: '/books',
    templateUrl: CONFIG.static_url + '/html/books.html',
    ...
})
.state('books.home', {
    url: '/home',
    templateUrl: CONFIG.static_url + '/html/books_list.html',
    ...
})
.state('books.detail', {
    url: '/:bookId',
    templateUrl: CONFIG.static_url + '/html/books_detail.html',
    ...
})

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

    我通过声明一个抽象状态实现了我所需要的:

    .state('books', {
        abstract: true,
        url: '/books',
        templateUrl: CONFIG.static_url + '/html/books.html',
        ...
    })
    .state('books.home', {
        url: '',
        templateUrl: CONFIG.static_url + '/html/books_list.html',
        ...
    })
    .state('books.detail', {
        url: '/:bookId',
        templateUrl: CONFIG.static_url + '/html/books_detail.html',
        ...
    })
    

    这意味着 /books 会同时加载 'books' 和 'books.home' 状态,而 /books/1 会同时加载 'books' 和 'books.detail' 状态,这正是我所需要的。

    【讨论】:

      【解决方案2】:

      我创建了working example here。这符合您的需求,因为只有两层嵌套。

      • books 是两个孩子的父母
        • books.home 填充中间区域 - 并且不是 books.detail 的父级
        • books.detail 替换了列表视图 - 但这意味着它的 $scope (books.home) 丢失了

      状态定义:

      .state('books', {
          url: '/books',
          views: {
            '@' : {
              templateUrl: 'layout.html',
            },
            'left@books' : { templateUrl: 'tpl.left.html',},
            'right@books' : { templateUrl: 'tpl.right.html',},
          },
        })
      .state('books.home', {
          url: '/home',
          templateUrl: 'list.html',
        })
      .state('books.detail', {
          url: '/:bookId',
          templateUrl: 'detail.html',
          controller: 'DetailCtrl'
        })
      

      查看here

      不过还有a different approach,我比较喜欢。列表视图是其子视图的父视图,因此它可以保留其 $scope,同时在细节之间导航。类似的东西讨论here

      【讨论】:

        【解决方案3】:

        不妨试试

        $urlRouterProvider.otherwise('/');
        .....
        .state('index', {
            url: '/',
            templateUrl: CONFIG.static_url + '/html/index.html',
            ...
        })    
        

        【讨论】:

        • 那是怎样的一个子状态?
        猜你喜欢
        • 1970-01-01
        • 2017-10-05
        • 2016-06-17
        • 2016-10-19
        • 2015-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多