angular-translate-based custom filter

1.1k views Asked by At

I'm using Pascal Precht's angular-translate module. I've got my translations namespaced, e.g.

{
  "customer.account.header.main": "stgsdefghdsf",
  "customer.account.column.name": "sdfszdfs"
  "customer.account.column.address": "dsghfg",
  "customer.account.enum.VALUE1": "dfsgsdf",
  "customer.account.enum.VALUE2": "sdfgsdfg"
}

and I'm using them in the templates this way:

{{ "customer.account.enum.VALUE1" | translate }}

It's working perfectly fine, but I need to make a custom translation filter, which would use translate beneath. I need to pass the namespace prefix, e.g.

{{ enumValue | translateEnum:"customer.account.enum" }}

where enumValue could be VALUE1, VALUE2, coming directly from the API.

Unfortunately, the following is NOT the solution, because this mechanism will be used by several higher-level mechanisms and it needs to accept just a filter (and possibly filter parameters), but not an expression such as ... + ... | filter

{{ "customer.account.enum." + enumValue | translate }}

The problem is that translate is asynchronous, since fetching language are asynchronous. I don't know how can I cope with that, because I've got no reference to the object which might be assigned after the then promise is resolved. I've got just the value. Just as the original translate uses.

So far I've tried those:

module.filter('translateEnumInstant', [
  '$translate', function($translate) {
    return function(input, namespace) {
      return $translate.instant(namespace + '.' + input);
    };
  }
]).filter('translateEnumFilter', [
  '$filter', function($filter) {
    var translateFilter;
    translateFilter = $filter('translate');
    return function(input, namespace) {
      return translateFilter(namespace + '.' + input);
    };
  }
]).filter('translateEnumPromise', [
  '$translate', function($translate) {
    return function(input, namespace) {
      return $translate(namespace + '.' + input);
    };
  }
]);

but none of them work fine. The first two are synchronous and they load the previous language, since they don't wait for the new language to be fetched via json. The last one returns a promise, so it just displays {} which is even worse.

Please tell me what I can do to write such directive.

1

There are 1 answers

0
JeanSeb On

This custom filter should work :

    .filter('translateEnum', function($filter) {
        var translateFilter = function (value, param) {
            return $filter('translate')(param+"."+value);
        }
        translateFilter.$stateful = true;
        return translateFilter;
    })