Search code examples
javascriptangularjsangular-translate

Map combobox options for translation


I have a bunch of state names in my data model that I want to map to different keys for translation, e.g.

  • Open -> state_open
  • New -> state_new
  • Wait for approval -> state_wait_for_approval

Currently my combo box is populated this way:

<select class="form-control select" id="client"
  ng-model="statusType"
  ng-change="setStatusType(statusType)"
  ng-options="statusType.name for statusType in statusTypes track by statusType.id">
  <option value="">-</option>
</select>

I have read that I can implement translation by doing this:

  ng-options="statusType.name | translate for statusType in statusTypes track by statusType.id">

However, this will assume that my translation keys are equal to the state names. I would rather like to map my state names to the translation keys mentioned above.

How can I implement this mechanism in Angular? I probably need some sort of custom directive (?). I'm new to Angular, so all hints are welcome.

I'm thinking of something like:

mapStateToTranslationKey(statusType.name) -> return "status_" + toLowerCase(replaceSpacesWithUnderscores(statusType.name))

Solution

  • I managed to solve the problem myself. Basically, I had to add this function to my controller:

    $scope.mapStateToTranslationKey = function(stateName) {
       return "state_" + stateName.toLowerCase().split(' ').join('_');
    };
    

    This function will convert the state name to lower case, replace all spaces by underscores and finally prepend the string state_. Ultimately, it returns a key, I can use for translation with angular-translate.

    In the view, I now have to call my function first and then use the translate keyword after the pipe symbol. This way the translation key will be used instead of the actual state name.

    <select class="form-control select" id="client"
       ng-model="statusType"
       ng-change="setStatusType(statusType)"
       ng-options="mapStateToTranslationKey(statusType.name) | translate for statusType in statusTypes track by statusType.id">
      <option value="">-</option>
    </select>