1
\$\begingroup\$

I wonder to know if there is any bad smell on my practice for i18n on Angular. I put the I18n translating function on Angular controller (because I don't know how to put it on HTML template file)

And about the i18n scope, I use this way I18n.t("city." + city_name) to indicate that the city_name is under "city" scope. Could I write it in this way I18n.t(city_name, scope: "city") to make it more understandable.

I appreciate every comment and suggestion to enhance my current solution.

Data structure

departures_lst is a list of countries' English name e.g.,: [US, China, Japan]

Each country has many cities name. e.g. [New York, LA, Boston]

Angular controller

App.controller("departures_ctrl", function($scope, $location, $http) {
    $http.get("/departures.json")
    .success(function (response) {
      $scope.departures_lst = response;
    });
    $scope.get_destinations = function(city_name) {
          return $location.url("/depart_from/" + city_name);
    };
    $scope.i18nCountryName = function(country_name) {
          return I18n.t("country." + country_name) + country_name
    };
    $scope.i18nCityName = function(city_name) {
          return I18n.t("city." + city_name) + city_name
    };
});

HTML teamplate?

<div class="panel panel-transparent" ng-repeat="departure in departures_lst">
    <h5>{{i18nCountryName(departure.country)}}</h5>
    <li class="col-sm-3 col-lg-3 col-xs-3" ng-repeat="city in departure.cities">
      <a ng-click="get_destinations(city)">
        <i class="fa fa-plane"></i>
        {{i18nCityName(city)}}
      </a>
    </li>
</div>
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Translations are UI logic, a different representation of the same data. They should stay on the template. On the other hand, country and city logic go in the controller. They should only be aware of the data, but not how it is represented.

The answer to this is to use Angular filters, and a separate service/factory/provider to hold the current language. The controller exposes the data to the UI, but the data is language-neutral.

Given that this is so similar, here's another answer where I explained how to use Angular filters with translations: https://codereview.stackexchange.com/a/116063/11919

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.