不带斜线的Angular Url和可选参数 [英] Angular Url without slash with optional parameters
问题描述
ui-router可选参数,不带斜杠 和如何定义可选参数使用UI-Router也不使用斜杠吗?没有足够的参数并且无效(至少对于我的情况,即没有斜杠的斜角路由的有效链接(href)).
Both ui-router optional param without trailing slash and How to define optional parameter using UI-Router without trailing slash as well? have insufficient arguments and invalid (at least for my scenario i.e. working links (href) for angular routes without trailing slashes) answers .
以下是示例html链接
Here are the example html links
<div>
<a ui-sref="home">Home</a>
| <a href="#/posting/">Post 1</a>
| <a href="#/posting">Post 2</a>
| <a href="#/posting/sami">Post 3</a>
| <a ui-sref="post">Post 4</a>
| <a ui-sref="post({nam:'sami'})">Post 5</a>
</div>
除了 Post 2 以外,上述所有链接都可以正常工作,因为我有一个可选参数,因此该链接的末尾至少需要一个斜杠
All of the above links are working fine except Post 2 because I have an optional parameter and so the link needs at least a slash at the end
我正在使用stateprovider
,而state
看起来像
I am using stateprovider
and a state
looks like
name: 'post',
val: {
url : '/posting/:nam',
views: {
v1: {
template: '<h4>Posting <label ng-if="stateParams.nam">{{stateParams.nam}}</label> </h4>',
controller: 'post',
resolve: {
deps: function ($ocLazyLoad) {
return $ocLazyLoad.load([{ name: appName, files: ['post.js'] }]);
}
}
},
params: {
nam: { squash: true, value: null }
}
}
}
如果我只能选择使用链接href
而不是ui-sref
推荐答案
如果您喜欢我尝试了@ egor.xyz解决方案,那么该解决方案将无法正常工作.检查
In case you like me tried @egor.xyz solution, and it didn't work. check the ui-router Frequent Questions, and you will find the following:
对于旧版本的ui-router,将此代码段添加到模块的config函数中.它将在$ urlRouterProvider上创建一个规则,该规则将所有缺少尾部斜杠的URL映射到相同的URL,但会附加尾部斜杠.
For older version of ui-router, add this snippet to your module's config function. It creates a rule on $urlRouterProvider that maps all urls that are missing a trailing slash to the same url but with the trailing slash appended.
$urlRouterProvider.rule(function ($injector, $location) {
var path = $location.url();
// check to see if the path already has a slash where it should be
if (path[path.length - 1] === '/' || path.indexOf('/?') > -1) {
return;
}
if (path.indexOf('?') > -1) {
return path.replace('?', '/?');
}
return path + '/';
});
为我工作.
这篇关于不带斜线的Angular Url和可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!