我目前正在本地化我的Angular网站,而angular-translate似乎是较小字符串的一个很好的选择。但是我有一些页面有很多静态html内容,比如ToS或about页面,我不想把它塞进JSON文件(混合了html标签等)。
那么有没有办法使用angular-translate(甚至没有那个模块)来保存部分视图中的内容(比如/partials/tos-en.html)并根据语言交换出来?
答案 0 :(得分:5)
您想要一种获取用户语言代码的方法。有了这个,你打算用语言代码作为名称的一部分呈现部分。
Angular翻译 模块有两种感兴趣的服务方式:
$translate.use()
返回用户的有效语言。不幸的是,如果在语言加载到页面之前调用服务方法,则可能会为null。
$translate.proposedLanguage()
返回"目标语言" - 意味着您可以调用$translate.use()
的值,但即使语言没有加载,此调用也会成功。拥有 language codes 的此列表,您可以使用它们为您打算支持的语言创建部分内容。
像
这样的东西<div ng-include="about-{{ $translate.proposedLanguage() }}.html">
</div>
答案 1 :(得分:1)
我建议您按下突出显示的部分路径。翻译小块文本适用于菜单条目,但最终会笨拙地读取整个文档。译者需要能够改变句子和段落结构等内容,使其看起来很自然。
要实现这一点,我会使用Apache's content negotiation (mod_negotiation)。您的角度代码仍然很简单,请参阅/partials/tos.html。 Apache然后根据需要提供tos.html.en,tos.html.fr或tos.html.de等。
设置内容协商确实需要使用Apache并且能够编辑配置文件,但学习起来并不是很复杂。我建议您按照说明启用首选语言cookie,这样您就可以提供一种语言选择机制来覆盖用户的浏览器语言设置。
答案 2 :(得分:1)
为每种语言创建HTML部分。收听控制器中的$ translateChangeSuccess事件,并在每次语言更改时创建部分URL。在ngInclude指令中使用视图中的URL。
V2更好的方法
您的控制器
myApp.controller('MyCtrl', ['$rootScope', '$scope', '$translate', function ($rootScope, $scope, $translate) {
($scope.setTranslatedPartials = function () {
$scope.translatedPartials = {
"partialOne": "/partials/partial_one_" + $translate.use() + ".html",
"partialTwo": "/partials/partial_two_" + $translate.use() + ".html"
//...
};
})();
$rootScope.$on("$translateChangeSuccess", function (event, next, current) {
$scope.setTranslatedPartials();
});
}]);
您的观点
<div ng-controller="MyCtrl">
<ng-include src="translatedPartials.partialOne"></ng-include>
<ng-include src="translatedPartials.partialTwo"></ng-include>
</div>
V1原创方法
您的控制器
myApp.controller('MyCtrl', ['$rootScope', '$scope', '$translate', function ($rootScope, $scope, $translate) {
/*Initialize first so you have it when coming back to the page without the langugage changing*/
$scope.partial = "/partials/" + $translate.use() + ".html"
$rootScope.$on("$translateChangeSuccess", function (event, next, current) {
$scope.partial = "/partials/" + $translate.use() + ".html"
});
}]);
您的观点
<div ng-controller="MyCtrl">
<ng-include src="partial"></ng-include>
</div>