Search code examples
javascriptangularjsangularjs-routing

Angular JS routing in multilanguage app is not working


I'm trying to implement a multilanguage app. i need to access the requested language by adding a two letter iso parameter to the URL before the controller name. for example: http://appPath/en/home http://appPath/fr/home http://appPath/ar/home

 $stateProvider
         .state('home', {
             url: '/home',
             templateUrl: baseTemplateUrl + "home.html",
             controller: 'homeController'
         })
        .state('login', {
            url: '/login',
            templateUrl: baseTemplateUrl + "login.html",
            controller: 'loginController'
        })
      .state('customers', {
          url: '/customers',
          templateUrl: baseTemplateUrl + "customers.html",
          controller: 'customersController'
      })
      .state('signup', {
          url: '/signup',
          templateUrl: baseTemplateUrl + "signup.html",
          controller: 'signupController'
      });

i'm using a basic stateprovider for routing right now. any idea how to change this to get this feature working?

Thank you in advance,


UPDATE


For anyone having the same problem, my solution was:

changed each state to the following

 .state('signup', {
              url: '/:lang/signup',
              templateUrl: baseTemplateUrl + "signup.html",
              controller: 'signupController',
              resolve: {
                  lang: ['$stateParams', function ($stateParams) {
                      document.cookie = "lang=" + $stateParams.lang;
                  }]
              }
          });

i save the value of the $stateParams lang into a cookie so you can access it through the app.run() and pass it to my translationService since the $stateParams is not initialized yet there.

this way your app will work only with html5mode=false. which means you will always see an ugly hashtag in the URL (http://path/#/{lang}/{controllername} andto solve this, i configured the $locationProvider this way:

 $locationProvider.html5Mode(true).hashPrefix('!');

and set the base url of the site by inserting inside the tag of your index.html file this line:

 <base href="/">

Thanks


Solution

  • Add the language code as a url parameter

    $stateProvider
         .state('home', {
             url: '/:langcode/home',
             templateUrl: baseTemplateUrl + "home.html",
             controller: 'homeController'
         });
    

    And in your controller, get langcode value using $stateParams

    $scope.language = $stateParams.langcode;