Further research
Here is my App:
'use strict';
var myApp = angular.module('myApp', []);
Here is my controller:
'use strict';
myApp.controller('PageController',
function PageController($scope, translationService, $rootScope) {
$rootScope.currentLanguage = 'en';
$rootScope.translations = translationService.getTranslations($scope.currentLanguage);
$scope.setLanguage = function(language) {
if (language === $scope.currentLanguage) {
return;
}
$rootScope.currentLanguage = language;
$rootScope.translations = translationService.getTranslations($scope.currentLanguage);
}
}
);
And here is the translationService:
'use strict';
myApp.service('translationService', function ($http, $q) {
var translationsCache = {};
return {
getTranslations: function(language) {
if (translationsCache[language]) {
return translationsCache[language];
}
var deferred = $q.defer();
// **** FAKE SOLUTION **** //
// I just return a resolve here as it doesn't really matter for this test.
if (language == 'sv') {
deferred.resolve({
"My first text unit": "Detta är min första text unit",
"I am a Pirate": "Jag är en Pirat"
});
} else if (language == 'en') {
deferred.resolve({
"My first text unit": "This is my first Text unit",
"I am a Pirate": "I'm a Pirate"
});
}
translationsCache[language] = deferred.promise;
return deferred.promise;
// **** END FAKE SOLUTION **** //
/*
// **** WORKING SOLUTION **** //
The probable real solution to fetching language JSON generated by Symfony somewhere
$http({method: 'GET', url: '/translations/'+language}).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function(data, status, headers, config) {
deferred.reject(status);
});
translationsCache[language] = deferred.promise;
return deferred.promise;
// **** END WORKING SOLUTION **** //
*/
}
}
});
So here is my directive that I came up with after some trial and error:
myApp.directive('translation', function($rootScope) {
return {
restrict: 'A', // Restrict to attribute
replace: true, // Replace current object by default, not for input though, see solution below
link: function(scope, element, attrs, controller){
// This will watch for changes in currentLanguage in your $rootScope
scope.$watch(function() {
return $rootScope.currentLanguage; // If this changes then trigger function (binding)
}, function(newVal, oldVal) {
// As we have translation as a promise this is how we do
$rootScope.translations.then(function(translations) {
// Does it exist, then translate it, otherwise use default as fallback
if (translations[scope.translation]) {
// Just some extra I found could be useful, set value if it is a button or submit. Could be extended.
if (element.prop('tagName') === 'INPUT' && (element.prop('type') === 'button' || element.prop('type') === 'submit')) {
return angular.element(element).val(translations[scope.translation]);
}
// Else just change the object to be the new translation.
return element.html(translations[scope.translation]);
}
// This is the fallback, and same as above, button and submit
if (element.prop('tagName') === 'INPUT' && (element.prop('type') === 'button' || element.prop('type') === 'submit')) {
return element.val(scope.translation);
}
return element.html(scope.translation);
});
});
},
scope: {
translation: "@" // Save the parameter to the scope as a string
}
}
});
And here are some examples of how to use it.
HTML:
<div class="container">
<div class="nav">
<button ng-click="setLanguage('en')">
<trans translation="English" />
</button>
<button ng-click="setLanguage('sv')">
<trans translation="Svenska" />
</button>
</div>
<hr />
<p><trans translation="I am a Pirate" /></p>
<p><trans translation="A text unit that doesn't exist" /></p>
<p><input type="button" translation="My button" /></p>
</div>
This would work as following using the jsFiddle:
http://jsfiddle.net/Oldek/95AH3/4/
This this solves:
- Fetch translations asynchronously
- Cache translations so switch is really fast
- Working with input / fields with value
- Store language in Local Storage
- Dynamically update the whole DOM on translation change
- Really quick, at least the scale I have tried
- Full and working solution to a common problem
Things to solve:
- Move out code that checks if it is an input field somewhere else
- Pluralisation
- Input Placeholder
- And other features a translation supports.
- Support parameters, see example:
<trans translation="Hello {{name}}" name="{{name}}">
- Scan the project with xgettext? and generate an YML or similar structure that can be translated in some software.
- Remove the temporary solution and use the working one commented out.
Other Comments
Please feel free to ask questions if you have, I'll provide info, and probably a jsFiddle some time soon in deemed needed.
/Marcus
<span>{{someVar | translate}}</span>
. – charlietfl