S Panfilov
S Panfilov

Reputation: 17581

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.

Upvotes: 1

Views: 2526

Answers (2)

pasine
pasine

Reputation: 11543

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

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

Upvotes: 2

Roy Daniels
Roy Daniels

Reputation: 6309

I think the best option will be to have a the urls to be something like http://mysite.com/somepath?lang=en and then you can just read lang directly from the url wherever you need to.

Upvotes: 0

Related Questions