首先,要做AngularJS国际化,需要下面三个模块
<script src="../angular/angular/angular.js"></script>
<script src="../angular/angular-translate/angular-translate.js"></script>
<script src="../angular/angular-translate-loader-static-files/angular-translate-loader-static-files.js"></script>
大家可以使用bower工具下载这些模块
bower install angular
bower install angular-translate
bower install angular-translate-loader-static-files
首先,我们这里那中文和英文举个🌰,先新建一个目录i18n,在这个目录下新建两个json文件cn.json, en.json.用来保存中英文对应的key和value.
cn.json:
{
"title": "这是标题"
}
en.json:
{
"title": "this is our title"
}
目录结构
这里就不把module模块和controller模块单独分到不同的文件离去了,全部写到html里:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../angular/angular/angular.js"></script>
<script src="../angular/angular-translate/angular-translate.js"></script>
<script src="../angular/angular-translate-loader-static-files/angular-translate-loader-static-files.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="testCtr">
<select class="language-switching" ng-model="cur_lang" ng-change="switching(cur_lang)">
<option value="en">English</option>
<option value="cn">简体中文</option>
</select>
<br/>
<span>测试:<span ng-bind="title"></span></span>
</div>
<script>
var app = angular.module('myApp', ['pascalprecht.translate'])
.config(['$translateProvider',function($translateProvider){
$translateProvider.useStaticFilesLoader({
prefix: '../i18n/',
suffix: '.json'
});
}]).controller('testCtr',['$scope', '$translate', function($scope, $translate){
var lang = window.localStorage.lang||'cn'; //默认加载中文对应的json文件
$translate.use(lang).then(function() {
$scope.title = $translate.instant('title');
});
$scope.switching = function(langKey){
$translate.use(langKey).then(function() {
$scope.title = $translate.instant('title'); //这里一定要注意:.use()是async方法,而.instant()是sync方法,所以一定要.use方法加载完之后再去取值,不然.instant()可能会在json文件还没加载完就执行,导致取值失败。
});
}
}]);
</script>
</body>
</html>
网友评论