AngularJS UI Router: Route conflict because of optional parameter

前端 未结 2 612
暖寄归人
暖寄归人 2021-01-20 16:26

I have a couple of routes in my AngularJS app, I\'m using UI-Router for routing between states/pages in my site. An issue I am having is that I have conflicting routes becau

相关标签:
2条回答
  • 2021-01-20 17:21

    Best practice would say that this should probably be a query string parameter rather than a route parameter since you are using it to filter out data. To do this with ui-router just define it like so:

    $stateProvider
    .state('home', {
       url: '/?filter'
    });
    

    Now just do

    $state.go('home', {filter: 'apples'})
    
    0 讨论(0)
  • 2021-01-20 17:29

    There is a working example

    The point here is to define home state as the last:

    // this url will be registered as first
    .state('login', {
          url: "/login",
          templateUrl: 'tpl.html',
    })
    // this as second
    .state('about', {
          url: "/about",
          templateUrl: 'tpl.html',
    })
    ...
    // this will be registered as the last
    .state('home', {
          url: "/:filter",
          templateUrl: 'tpl.html',
          params: {
            filter: { squash: true, value: null }
          }
    })
    

    UI-Router iterates the registered states in that order, and tries to find out first match. This way - all other states (login, about) will have precedence of 'home' state...

    Check it here

    0 讨论(0)
提交回复
热议问题