angular-translate 2.7.2, AngularJS 1.4.2
I have the requirement (don't ask...) that for every translatable snippet of text on my site, there are actually two candidate translations of which one is derived by adding a prefix to the translationId.
Example translations:
greeting => "hi"
abc.greeting => "yo"
abc.
is my prefix here. If abc.greeting
can be translated, then its translation should be shown, otherwise fall back to the translationId greeting
if available, and if neither translationId exists: give up, handle the missing translation.
I want to wrap this behavior into a directive so that I can still use conveniently it like this:
<p my-translate="greeting"></p>
which produces either <p>yo</p>
or <p>hi</p>
depending on the existance of translationIds. I came up with this code in my directive that essentially wraps $translate
:
function translateWithFallback(translationId, translationValues, element, prefix) {
function successHandler(translation) {
element.html(translation);
}
function failureHandler(translationId) {
element.html("???" + translationId + "???");
}
var prefixedTranslationId = prefix + translationId;
$translate(prefixedTranslationId, translationValues).then(successHandler, function() {
$translate(translationId, translationValues).then(successHandler, failureHandler);
});
}
Soon I realized that this solution is lacking compared to the angular-translate directive: It does not notice language selection (I guess I'd need to listen on $translateChangeSuccess
) and does not set up watchers for changes to translationId and translationValues. Doing all that and in an efficient manner is what the angular-translate directive already does: https://stackoverflow.com/a/23866441
So my question is: how can I extend or reuse the translate directive but with a fallback regarding translationIds? Any ideas?