我正在玩Angular JS,并会在那里为你们的主人提供一些意见:D
我正在做的是实现我自己的本地化代码(我知道,我知道,那里有库,我应该使用它们。但要明白我这样做是为了提高我对框架的理解)
有一个显示语言列表的选择框,当我更改语言时,术语会被翻译。
HTML:
<div ng-controller="LanguageController">
<div><span>Current Language: {{language}}</span></div>
<div><span>Term 1: {{dictionary.term1}}</span></div>
<div><span>Term 2: {{dictionary.term2}}</span></div>
<div>
<select ng-model="language" ng-change="changeLanguage(language)">
<option ng-repeat="(key, value) in lanugages" value="{{key}}">{{key}}</option>
</select>
</div>
</div>
App.js文件
(function(){
return angular.module('testApp', ['ngRoute'])
.controller('LanguageController',['$scope',function($scope){
$scope.lanugages = {
'English':{
'term1':'This is Term 1 in English',
'term2':'This is Term 2 in English'
},
'French':{
'term1':'This is Term 1 in French',
'term2':'This is Term 2 in French'
},
'Vietnamese':{
'term1':'This is Term 1 in Vietnamese',
'term2':'This is Term 2 in Vietnamese'
}
};
$scope.language = 'English';
$scope.dictionary = $scope.lanugages[$scope.language];
$scope.$watch('language', function() {
$scope.dictionary = $scope.lanugages[$scope.language];
});
$scope.changeLanguage = function(lang){
$scope.language = lang;
}
}]);
})();
请注意,我添加了$watch
语句,该语句侦听language
变量中的更改,并根据dictionary
的值更新language
的值。
我想要做的是知道,如果有其他(可能更复杂)的方式来监听language
中的更改并更新dictionary
而不使用$watch
先谢谢你:D
-M
答案 0 :(得分:1)
编辑:在回复评论时,这是另一个版本:http://jsfiddle.net/dn3w41cx/9/
根本不需要控制器中的数据工作。
以下是代码:
的javascript
function LanguageController($scope) {
$scope.languages = [
{
name:'English',
'term1': 'This is Term 1 in English',
'term2': 'This is Term 2 in English'
},
{
name:'French',
'term1': 'This is Term 1 in French',
'term2': 'This is Term 2 in French'
},
{
name:'Vietnamese',
'term1': 'This is Term 1 in Vietnamese',
'term2': 'This is Term 2 in Vietnamese'
}
];
}
HTML
<div ng-app>
<div ng-controller="LanguageController">
<div><span>Current Language: {{language.name}}</span>
</div>
<div><span>Term 1: {{language.term1}}</span>
</div>
<div><span>Term 2: {{language.term2}}</span>
</div>
<div>
<select ng-options="item.name for item in languages" ng-model="language"
ng-init="language=languages[0]">
</select>
</div>
</div>
</div>
旧答案:
如果你想要很好的语法,那么你可以在changeLanguage函数中实现类似的东西:http://jsfiddle.net/dn3w41cx/6/
否则,您可以在javascript中进行任何特殊更改,例如此小提琴:http://jsfiddle.net/dn3w41cx/5/