本文介绍了使用 ui-router 和 angular-translate 本地化 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ui-router 进行路由,使用 angular-translate 进行翻译.我想要实现的是将所选语言绑定到 url,如下所示:

I am using ui-router for routing and angular-translate for translations. What i would like to achieve is having the selected language bind to the url like so:

www.mydomain.com/en/
www.mydomain.com/ru/
www.mydomain.com/en/about
www.mydomain.com/ru/about

它会做出相应的反应.

试图寻找例子,但没有找到任何东西.如果有人实施了类似的解决方案,我很想听听您是如何做到的.

Tried to look for examples, but did not find anything.If someone implemented similar solution, i would love to hear how you did it.

谢谢

推荐答案

我使用了一些类似的东西:

I use something along these lines:

CoffeeScript

angular.module('app')
.config([
  '$stateProvider'
  ($stateProvider) ->
    $stateProvider.state 'app',
      abstract: true
      url: '/{locale}'
    $stateProvider.state 'app.root',
      url: ''
    $stateProvider.state 'app.root.about',
      url: '/about'
])

JavaScript

angular.module('app').config([
  '$stateProvider', function($stateProvider) {
    $stateProvider.state('app', {
      abstract: true,
      url: '/{locale}'
    });
    $stateProvider.state('app.root', {
      url: ''
    });
    return $stateProvider.state('app.root.about', {
      url: '/about'
    });
  }
]);

有了这个,您可以将 $stateParams 注入您的控制器并访问那里的语言环境:

With this, you can inject $stateParams into your controller and get access to the locale there:

CoffeeScript

angular.module('app')
.controller('appCtrl', [
  '$scope', '$stateParams'
  ($scope, $stateParams) ->
    $scope.locale = $stateParams.locale
])

JavaScript

angular.module('app').controller('appCtrl', [
  '$scope', '$stateParams', function($scope, $stateParams) {
    return $scope.locale = $stateParams.locale;
  }
]);

或者,如果您想自动影响整个页面,请在应用程序控制器或类似的地方使用 $stateChangeStart 事件:

Or, if you want to affect the whole page automatically, use the $stateChangeStart event in an application controller or similar:

CoffeeScript

$scope.$on '$stateChangeStart', (event, toState, toParams, fromState, fromParams) ->
  $translate.use(toParams.locale)

JavaScript

$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
  $translate.use(toParams.locale);
});

请注意,如果您使用的是 angular-translate v1.x,则应使用 $translate.uses 而不是 $translate.use.

Note that if you're using angular-translate v1.x you should use $translate.uses instead of $translate.use.

这篇关于使用 ui-router 和 angular-translate 本地化 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 09:20