问题
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 .
Live Demo Link
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>
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
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 }
}
}
}
How can i have a valid link without trailing slash if I have only option to use links href
and not the ui-sref
回答1:
You can use $urlMatcherFactoryProvider.strictMode(false);
in config
回答2:
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:
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 + '/';
});
Worked for me.
来源:https://stackoverflow.com/questions/39082825/angular-url-without-slash-with-optional-parameters