Angular UI-Router嵌套路由id

Angular UI-Router nested route with id

我的应用程序中有两条路线,通过 ui-router:

相互嵌套

app/locations/locations.js

'use strict';

angular.module('treasuremapApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('locations', {
        url: '/locations',
        templateUrl: 'app/locations/locations.html',
        controller: 'LocationsCtrl'
      });
  });

和app/locations/location/location.js

'use strict';

angular.module('treasuremapApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('location', {
        url: '/locations/:id',
        templateUrl: 'app/locations/location/location.html',
        controller: 'LocationCtrl'
      });
  });

这在大多数情况下都可以正常工作,但是当我第一次在我的位置列表中单击一个时,它显示得很好,甚至后退按钮也可以,但是当我然后输入 /locations 进入 URL 栏(没有后退按钮的任何其他方式),路由器似乎试图用控制器和模板打开 "lower" 路由,但当然缺少 url 那么

我觉得我对 ui-router 的理解有点缺陷,所以有人可以向我解释一下,我在这里做错了什么。

也许您在 URL 中输入了 /locations/ 而不是 /locations。输入 /locations/ 将触发第二条路由,因为 ui-router 会期望 :id 等于 (empty).

如果您希望它的行为有所不同,另请参阅此常见问题解答:https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-make-a-trailing-slash-optional-for-all-routes

How can I have my routes be activated when the url contains either a trailing slash or not?

Set strictMode to false in your config block:

$urlMatcherFactoryProvider.strictMode(false)