I have been working on a system that manages translations in my factory. I set the language as a string and then use a filter to update the view when the language changes.
Everything works fine if I define the language in the view beforehand, but when I try to change the language using a button click, nothing happens.
Can someone please help me figure out what I might be doing wrong?
This is a snippet of my view:
<div ng-app="testApp">
<div ng-controller="myController">
<p >{{ data.title | translate }}</p>
<p >{{ data.text }}</p>
<button type="button" ng-click="changeLanguage('en')">English</button>
<button type="button" ng-click="changeLanguage('sl')">Slovene</button>
</div>
</div>
This is part of my script:
angular.module('langService', [])
.factory('Language', function() {
var currentLanguage = 'en';
return {
setCurrentLanguage: function(value) {
currentLanguage = value;
},
getCurrentLanguage: function() {
return currentLanguage;
}
}
});
var testApp = angular.module('testApp', ['langService']);
testApp.controller('myController', function ($scope, Language) {
$scope.data = {
title: 'PAGE_TITLE',
text :'some random page text'
};
$scope.changeLanguage = function(value) {
Language.setCurrentLanguage(value);
}
});
testApp.constant('Translations', {
en: {
'PAGE_TITLE': 'Hi!'
},
sl: {
'PAGE_TITLE': 'Živjo!'
}
});
testApp.filter('translate', function(Translations, Language) {
return function(input) {
return Translations[Language.getCurrentLanguage()][input] || '';
};
});
I've put together an example on codepen to test it out before incorporating it into a project.
Any assistance would be greatly appreciated.