Angular-GetText Snippets


Code Snippet

In my last post I showed you how to get up and running using the Angular-GetText using element annotation and filters using the translate directive. In this post I will cover a code snippet or two and demonstrate how I solved certain problems.

Grouped List

The first problem that I wanted to demonstrate was the grouped drop down list items. This makes use of an object array. Lets take a look at the html snippet shown below:

<ul class="dropdown-menu" style="background-color: black;">
    <div id="productList" ng-repeat="product in productList | filter:filterProductType">
        <b style="color:orange">{{product.productType | translate}}</b>
        <li ng-repeat="product in productList | filter:{productType: product.productType}">
            <a href="" ng-click="navigateToProduct(product.url, product.screenType)" id="id{{product.name}}">
                <img src="{{product.imgUrl}}" />{{product.name | translate}}
            </a>
        </li>
    </div>
</ul>

The way this code works is by pulling values from an object array of products that are grouped by product type using a filter. For more in depth information on AngularJS filters and how they work, please visit the AngularJS: Developers Guide: Filters located here. Here is an example of a product object inside the product list.

{
    productType: '',
    url: '',
    screenType: '',
    name: '',
    imgUrl: ''
};

Everything inside our <div> container tag is the template that we will use to display the items in our product list. The next tag of interest is our <b> container tag. The information inside the tag {{product.productType | translate}} tells us that the property ‘productType’ on the product object will be translated and then used for display purposes. Next there is a list item template <li> with the ng-repeat directive that will iterate through every product in the product list filtered by the current product type. If I have values that are grouped together by product type, all of the values listed under that type will be listed in a sub-list. Finally the anchor and image tags will format the display of your product list. While this might look complex at first, the code to create this effect is pretty straight forward.

Create A Language Service

You may find yourself needing to perform the same custom translation functions over several different JavaScript files. In this case, it is best to create a language service that can service that need rather than duplicate the code. The following example will demonstrate how to create a language service using the AngularJS factory recipe.

angular.module('Main', ['gettext'],
    .factory('LanguageService', ['gettextCatalog', function(gettextCatalog) {

        var langService = {};

        langService.changeCurrentLanguage = function (languageCode) {
            gettextCatalog.currentLanguage = getFormattedLanguageCode(languageCode);
            gettextCatalog.debug = true;
        };

        langService.getTranslatedString = function (str) {
            return gettextCatalog.getString(str);
        };

        function getFormattedLanguageCode(str) {
            var splitLocale = str.split('-');
            var localeCode = 'en_US';

            if (splitLocale.length > 1) {
                localeCode = (splitLocale[0].toLowerCase() + '_' + splitLocale[1].toUpperCase());
            }
            else {
                localeCode = splitLocale[0].toLowerCase();
            }

            return localeCode;
        }

        return langService;
    }]);

As you can see from the snippet above I have created an Angular module called ‘Main’ and injected the Angular-GetText into it. I’ve created a new factory called ‘LanguageService’ and created the service inside. Notice that I have to create the object and then add the methods to it before returning. So far everything inside is just plain old JavaScript. I’ve added three methods to the service, two of them public and one private.

  • The changeCurrentLanguage method will change the language that Angular-GetText will use to translate the strings on the web page. This can be used now globally in your application by injecting this service and calling the method.
  • The getTranslateString method is fairly straight forward, it will simply get the translation for whatever string you pass into it.
  • The private method getFormattedLanguageCode was needed because all of my translations are identified by their code with an underscore. But there are time when I receive the code with a dash. This method transforms the string into something that I can use. For example: en-en or en-EN will become en_EN.

Select Directive

Another opportunity for success came when I ran across the ng-select directive. This didn’t work with a filter the way that I expected so I had to do come up with another way. Do you remember that ‘LanguageService’ we just went over? Good, I’m going to show you how to use it here. Let’s take a look at the code.

<div>
    <select class="form-control" id="selectLocale" ng-model="selectedLocale"
            ng-options="locale as translate(locale.name) for locale in locales">
    </select>
</div>

This snippet shows the select for selecting the locale that you want to use. Pay close attention to the ng-options tag. This iterates through the locales object array to display the data in the drop down. Please take note of the as translate(locale.name) portion of the string. This can be used because I have injected the ‘LanguageService’ into the controller of the application and created the following function.

$scope.translate = function(str) {
    return LanguageService.getTranslatedString(str);
};

Now every time the select iterates through the array it will call this function to translate the string for you. For more information on the select tag, check out AngularJS: API: select directive in the documentation.

Hopefully this gives you some more clarity going forward on how to translate your application. If you have questions or a specific scenario that you would like help with, please let me message me and I’ll try to get back to you as soon as I can.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s