Sergey Panfilov Sergey Panfilov - 3 months ago 21
Javascript Question

How to add dynamic prefix to AngularJS routes

What i what is make localized urls like:



Let pretend that we always know user lang.

angular.module('website', [])
.constant('ROUTES', (function () {
var lang = 'eng'; // just for example
return {
SOME_PATH: '/' + lang + '/somepath'
}
})())
.config([..., '$locationProvider', 'ROUTES', function(..., $locationProvider, ROUTES {
$routeProvider.when(ROUTES.SOME_PATH, {templateUrl: 'pages/some_page.html', controller: 'SomePageController'});
$locationProvider.html5Mode(true);
}])
.run(['$rootScope', 'ROUTES', function ($rootScope, ROUTES) {
$rootScope.ROUTES = ROUTES;
}]);


So, if i am add link in html, everithing works:

<a href="{{ROUTES.SOME_PATH}}">Some path</a>


After i am click a link routing work just as planned.
But if i refresh page or came by direct link ("http://example.com/eng/somepath"), i cannot reach any page and see a 404 page.

Answer

Wouldn't be easier to map the route with the $routeProvider?

$routeProvider.when('/:langId/:somepath', 
    {
     controller: 'languageHandlingController'
    })