Hey everyone, I'm experimenting with Angular JS and would love to hear some insights from all you experts out there :D
What I'm currently working on is creating my own localization code. Yes, I know there are existing libraries available, but I prefer building it myself to enhance my understanding of the framework.
I have a select box that lists different languages, and when I switch the language, the terms should be translated accordingly.
Here's the 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>
And here's the App.js file:
(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;
}
}]);
})();
I've included a $watch
statement to monitor changes in the language
variable and update the dictionary
accordingly.
I'm curious if there's a more advanced method to track changes in language
and update
dictionary</code without relying on <code>$watch
.
Thanks for your help! :D
-M