Search code examples
javascriptangularjsmongodbangular-translate

Angular-translate, translate content from database


I'm using AngularJS and angular-translate for the internationalization. However my site has products loaded from the database. Since I want to avoid making 3 different collections and loading one based on language, I want to use one and translate the content dynamically.

So far I've tried the straightforward way, by entering the following in my database:

"name" : "{{'product_general' | translate}}",

However it just renders it as a string on my site. Is there a possible solution to my problem?


Solution

  • Try storing just the placeholder in the database. The part in the single quotes in your example:

    product_general

    Once you read it from the database, put that reference in the view and it should work.

    In the controller:

    $scope.valueReadFromDb = ...;
    

    In the view:

    {{ valueReadFromDb | translate }}
    

    Alternatively, if you want to translate something in the controller side instead of the view, for whatever reason, you can inject $filter in your controller and do something like this:

    var translate = $filter('translate');
    
    $scope.someVariable = translate('PLACEHOLDER');