问题
I added a when()
method to set/validate a route prefix, which looks something like this:
$urlRouterProvider.when(/[a-z]{2}-[a-z]{2}/, [
'$match','myValidatorSrv',
function($match, myValidatorSrv) {
if ( myValidatorSrv.validate($match[0]) ) return true;
// …
return $match.input.replace($match[0],'en-us');
}
]);
$urlRouterProvider.when(/(?![a-z]{2}-[a-z]{2})/, [
'$match','myValidatorSrv',
function($match, myValidatorSrv) {
// …
return $match.input.replace('/', '/en-us/');
}
]);
The re-writing happens as I expect, and I get /en-us/home
(GET /home
).
My states are set up like so:
$stateProvider
.state('base', {
abstract: true,
url: '/{locale}'
})
.state('base.home', {
url: '/home',
views: {
'home@': {
templateUrl: '/partials/home.html'
}
}
});
The problem is, with the when()
s in place, the states no-longer match (the view does not get loaded); even when I manually go to /en-us/home
, the state still does not get triggered.
Do I need to do something special to get $state to re-evaluate?
回答1:
There is a working plunker
This would be the adjusted .when()
$urlRouterProvider.when(/[a-z]{2}-[a-z]{2}/,
['$match', function($match) {
var supported = ['cs-cz', 'en-us', 'en-gb'];
var isSupported = supported.indexOf($match[0]) >= 0 ;
if(isSupported){
return false;
}
return $match.input.replace($match[0], 'en-us');
}
]);
$urlRouterProvider.when(/^(.(?![a-z]{2}-[a-z]{2}))/,
['$match', function($match)
{
return $match.input.replace('/', '/en-us/');
}
]);
That all is related to the:
$urlRouterProvider - when() for redirection
small cite:
handler
as FunctionIf the handler is a function, it is injectable. It gets invoked if $location matches. You have the option of inject the match object as $match
The handler can return:
- falsy to indicate that the rule didn't match after all, then $urlRouter will continue trying to find another one that matches.
- a String, which is treated as a redirect and passed to $location.url()
- nothing or any truthy value tells $urlRouter that the url was handled
Check it here
来源:https://stackoverflow.com/questions/26172461/angular-ui-router-urlrouterprovider-when-handler-result-ignored-by-state