我正致力于将我的 Angularjs 代码从 ng-router 迁移到 UI-Router。在我的 ng-router 中,我有可选参数,但是我意识到 ui-router 不支持支持可选参数的同样简单的方法。以下是我现有 ng-router 模块的路由。
//Define routes for view using ng-router
$routeProvider.
when('/my-app/home/:userid?', {
templateUrl: '/templates/partials/home/HomeView.html',
controller: 'HomeViewController'
})
.when('/my-app/:productKey/:userid?', {
templateUrl: '/templates/partials/productpage/ProductPageView.html',
controller: 'ProductViewController'
})
.otherwise({redirectTo: '/my-app/home'});
注意:如果您看到“:userid”参数在这里非常顺利地作为可选参数实现。
我尝试在 ui-router 中跟随,但同样不起作用。我浏览了很多帖子,有人建议复制路线。我真的不想复制,因为它会使代码变脏。
//Set the default route
$urlRouterProvider.otherwise('/my-app/home');
//Define routes for view (Please make sure the most matched pattern is define at top)
$stateProvider
.state('viewallcards', {
url: '/my-app/home/:userid',
templateUrl: '/templates/partials/home/HomeView.html',
controller: 'HomeViewController'
})
.state('productpage', {
url: '/my-app/:productKey/:userid',
templateUrl: '/templates/partials/productpage/ProductPageView.html',
controller: 'ProductViewController'
});
此处/my-app/home/有效,但/my-app/home 无效。如何使它也没有尾部斜杠?
另外,关于同一问题的帖子让我感到惊讶,因为它在 ui-router 中不受支持。它还有效吗? 请帮忙。
最佳答案
我们可以使用 params : {}
对象来完全按照我们的需要定义 userid
(即可以省略) .
在此处查看有关params
的更多详细信息:
Angular ui router passing data between states without URL
$stateProvider
.state('viewallcards', {
url: '/my-app/home/:userid',
params: {
userid: {squash: true, value: null }, // this will make both links below working:
// #/my-app/home
// #/my-app/home/
},
...
})
.state('productpage', {
url: '/my-app/:productKey/:userid',
...
})
关于javascript - 如何使用没有尾部斜杠的 UI-Router 定义可选参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30720672/