Angular $routeProvider: Why does CRUD new route no

2019-06-04 01:28发布

问题:

I'm building an Angular app with RESTful CRUD actions. Almost everything is working except for the /users/new route ~ it displays the show view instead of new view specified in $routeProvider. However, '/new' does work. I'm not getting any feedback in the js console. Any ideas or examples I should read?

App.config [
  '$routeProvider'
  '$locationProvider'

  ($routeProvider, $locationProvider, config) ->
    $routeProvider
      .when('/',
        templateUrl: '/partials/home.html'
      ).when('/users',
        templateUrl: 'partials/users/index.html'
        controller: 'UserIndexCtrl'
      ).when('/users/:id',
        templateUrl: 'partials/users/show.html'
        controller: 'UserShowCtrl'
      ).when('/users/:id/edit',
        templateUrl: 'partials/users/edit.html'
        controller: 'UserEditCtrl'
      # why does following not work:
      ).when('/users/new',
        templateUrl: 'partials/users/new.html'
        controller: 'UserNewCtrl'
      # but this does:
      ).when('/new',
        templateUrl: 'partials/users/new.html'
        controller: 'UserNewCtrl'
      ).otherwise(redirectTo: '/')
    $locationProvider.html5Mode(true)
]

回答1:

The $routeProvider try to test url pattern defined from TOP to BOTTOM.
So the URL pattern /users/new match /users/:id defined 3rd before /users/new defined 5th.

If you define /users/new before /users/:id, I expect that it would work properly.

The code should be like below.

App.config [
  '$routeProvider'
  '$locationProvider'

  ($routeProvider, $locationProvider, config) ->
    $routeProvider
      .when('/',
        templateUrl: '/partials/home.html'
      ).when('/users',
        templateUrl: 'partials/users/index.html'
        controller: 'UserIndexCtrl'
      # you should write it before '/users/:id'
      ).when('/users/new',
        templateUrl: 'partials/users/new.html'
        controller: 'UserNewCtrl'
      ).when('/users/:id',
        templateUrl: 'partials/users/show.html'
        controller: 'UserShowCtrl'
      ).when('/users/:id/edit',
        templateUrl: 'partials/users/edit.html'
        controller: 'UserEditCtrl'
      ).when('/new',
        templateUrl: 'partials/users/new.html'
        controller: 'UserNewCtrl'
      ).otherwise(redirectTo: '/')
    $locationProvider.html5Mode(true)
]