Reputation: 4044
I have written my own simple translation filter:
angular.module('app')
.filter('translate', translate);
translate.$inject = ['translation', 'language'];
function translate(translation, language) {
return function(value) {
var result = translation[language.getLanguage()][value];
if (!result) {
throw new Error("no translation");
}
return result;
}
}
The language can change: after logging in, the user might use a different language than the default one.
However, the filter doesn't re-apply: the old translation is still displayed. Is there a way to execute the filter again when the language changes?
In this case, the dependency 'language' is a service which contains the language. getLanguage() returns this language.
Upvotes: 2
Views: 72
Reputation: 2022
You're taking an interesting but flawed approach for this. Angular filters are reapplied only when the value being filtered is changed, so they aren't suited for actually changing the inputs themselves. You could do this employing a stateful filter though, which is a feature added in Angular 1.3.
You only need to set the $stateful property to true in your filter and make sure to inject a dependency. This way, angular will refresh the filter when necessary.
Here's an example based on your code.
filter('translate', ['translation', 'language', function (translation, language) {
function translationFilter(value) {
var result = translation[language.getLanguage()][value];
if (!result) {
throw new Error("no translation");
}
return result;
}
translationFilter.$stateful = true;
return translationFilter;
}]);
Note that stateful filters may reduce performance, so you can take a different approach if this gives you trouble.
The better solution would be using angular-translate, which not only handles all of this for you in a more mantainable way, but also offers a (stateful) filter doing the exact thing you want to do.
Take a look at this API, for example.
Upvotes: 2