Angular Nested状态未按预期工作

时间:2014-09-02 07:42:11

标签: angularjs nested state angular-ui-router

有人能看出为什么这不起作用? /series未加载图库,但/series/:id/seasons部分正在运行。 (它不是缺少ng-view问题,请参阅下面的工作代码!)

angular.module('xbmcremoteApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('series', {
        url: '/series',
        templateUrl: 'app/series/series.html',
        controller: 'SeriesCtrl'
      }).state('series.gallery', {
        url: '',
        templateUrl: 'app/series/series-gallery/series-gallery.html',
        controller: 'SeriesGalleryCtrl'
      }).state('series.seasons', {
        url: '/:id/seasons',
        templateUrl: 'app/series/seasons/seasons.html',
        controller: 'SeasonsCtrl'
      });
  });

如果我改变它,它可以工作,但那不是我想要的:

angular.module('xbmcremoteApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('series', {
        url: '',
        templateUrl: 'app/series/series.html',
        controller: 'SeriesCtrl'
      }).state('series.gallery', {
        url: '/series',
        templateUrl: 'app/series/series-gallery/series-gallery.html',
        controller: 'SeriesGalleryCtrl'
      }).state('series.seasons', {
        url: '/series/:id/seasons',
        templateUrl: 'app/series/seasons/seasons.html',
        controller: 'SeasonsCtrl'
      });
  });

EDIT和soltuion:
我的帖子缺少一些信息。为了清楚说明:
我希望在调用/series网址时显示图库。我想用季节网址来展示季节。没有更多意见!
找到一个非常简单的解决方将abstract属性设置为true会强制stateprovider使用子视图。

....
.state('series', {
    abstract:true,  //adding this line makes the states work as expected
    url: '/series',
    templateUrl: 'app/series/series.html',
    controller: 'SeriesCtrl'
  })
....

1 个答案:

答案 0 :(得分:1)

在第一个定义中,网址/series被评估为根状态'series'

.state('series', {
    url: '/series',          // url evaluation will stop here, because
    ...                      // there is a match for /series
  }).state('series.gallery', { // this will never be reached via url
    url: '',                   // but ui-sref="series.gallery" will work
    ...

虽然第二个映射确实区分了两个状态,而'/ series'将导航到'series.gallery'状态:

.state('series', {
    url: '',                   // url like "#" will navigate there
    ...
  }).state('series.gallery', { // url /series will trigger this child state
    url: '/series',
    ...

一般来说,如果状态应该是url唯一的,那么每个状态都应该有一些定义。所以最有可能的是这应该是有意义的:

.state('series', {
    url: '/',                   // url like "#/" will navigate to series
    ...
  }).state('series.gallery', { // url '/series' will trigger this
    url: '^/series',
    ...

检查神奇的标志: ^

  

如果您想要绝对网址匹配,则需要在网址字符串前加上一个特殊符号'^'