Search code examples
javascriptangularjsangular-translate

angular-translate translate dict in controller


In my app I use https://github.com/angular-translate/angular-translate for localization. But I cant't understand how to translate dict values in my controller:

$scope.rx_usart_names = [
    {'val': 0, 'name': 'UART 1'},
    {'val': 2, 'name': 'UART 3'},
    {'val': 3, 'name': 'UART 4'},
    {'val': 5, 'name': 'UART 6'}
];

Then I show it in template like:

<md-select placeholder="Receiver Port" ng-model="RFDump.set.rx_usart">
  <md-option ng-repeat="option in rx_usart_names" ng-value="option.val">
    {{ option.name }}
  </md-option>
</md-select>

If I use: $translate.instant('UART 1') then when I change language, my value not changed.

If I use $translate('UART 1') then it returns promise.

Example:

http://jsfiddle.net/ayqoeuyy/6/


Solution

  • You can use the translate filter...

    translate FILTER SOLUTION: (JsFiddle)

    HTML:

    <md-select>
      <md-option ng-repeat="option in vm.rx_usart_names">
        {{ option.name | translate }}
      </md-option>
    </md-select>
    

    APP CONFIG:

    app.config(function($translateProvider) {
      $translateProvider.translations('en', {
        UART1: 'UART1 (English)',
        UART2: 'UART2 (English)'
      });
      $translateProvider.translations('de', {
        UART1: 'UART1 (German)',
        UART2: 'UART2 (German)'
      });
      $translateProvider.preferredLanguage('en');
    });
    

    CONTROLLER:

    function MyCtrl($translate) {
    
      var vm = this;
    
      vm.rx_usart_names= [{
        'val': 0,
        'name': 'UART1'
      }, {
        'val': 2,
        'name': 'UART2'
      }];
    
      vm.changeLanguage = function(langKey) {
        $translate.use(langKey);
      };
    }
    

    I know that is not the fastest way to use a filter if you have many keys to translate, but even in the example of the angular i18n docs they're using it. This is not a pure controller solution, but at least it works well. I hope someone post a better way to do it... Good luck