internationalizing your angularjs app

36
International izing Your Angular App Internationalization & Localization Basics

Upload: sarah-hudson

Post on 13-Apr-2017

1.452 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Internationalizing Your AngularJS App

Internationalizing Your Angular AppInternationalization & Localization Basics

Page 2: Internationalizing Your AngularJS App

Internationalization Basics

Page 3: Internationalizing Your AngularJS App

What is localization?“Localization refers to the adaptation of a

product, application or document content to meet the language, cultural and other

requirements of a specific target market (a locale).”-- W3C

Page 4: Internationalizing Your AngularJS App

What is localization? (cont.)Detecting the user’s localeWriting text in a way that the user understands based on his

locale, whether through languages, dialects, or idiomsDisplaying data in a way that makes sense to the user based

on his localeThis includes: date formats, currency, time formats

Ensuring graphics and design elements communicate the intended message

Includes colors, symbols, and iconsAlso known as l10n

Page 5: Internationalizing Your AngularJS App

What is internationalization?“Internationalization is the design and

development of a product, application or document content that enables easy

localization for target audiences that vary in culture, region, or language.”

-- W3C

Page 6: Internationalizing Your AngularJS App

What is internationalization? (cont.)Building your app with the flexibility of supporting multiple

localesMultiple languages, currencies, countries, name displays,

address displays, date and time formatsAbility to change the language, whether through browser

detection or allowing the user to choose the language of display

Offering multiple locales to the userDetermining which character sets to use (Typically Unicode)Also known as i18n

Page 7: Internationalizing Your AngularJS App

Methods of supporting i18n and l10n1.Selecting a region and being redirected to

another page that supports that locale:a.Subdomains for each locale that serves up different

HTML contentb.Separate websites for each locale

2.JavaScript for showing/hiding or swapping out content

Page 8: Internationalizing Your AngularJS App

Detecting the browser’s locale1. Can use the browser object:

if(navigator.language !== undefined && navigator.language !== null){ var language = navigator.language; language = language.toLowerCase();} else { //Handles IE var language = navigator.userLanguage; language = language.toLowerCase();};

Page 9: Internationalizing Your AngularJS App

Angular i18n

Page 10: Internationalizing Your AngularJS App

The $locale serviceAngular comes with built in support for many locales. Like many of the extra Angular services (i.e., ngRoute, ngResource, ngMocks), you’ll have to install.

bower | npm install angular-i18n

The folder installed will contain locale files for handling the date, currency, and number filters.

angular.module(‘myI18nApp’, [‘ngLocale’, ‘tmh.dynamicLocale’, ‘pascalprecht.translate’])

Page 11: Internationalizing Your AngularJS App

Built in filters for i18ndate: Takes a string parameter which translates into a format. (like: {{dateObj.startDate | date: ‘shortDate’}}

shortDate: In en-us, formats as 09/24/2015longDate: In en-us, formats as September 24, 2015fullDate: In en-us, formats as Thursday, September 24, 2015

currency: Appends or prepends the currency symbol based on the current user’s locale, as well as manages commas and decimals.

Note: Watch out! It only translates the symbol, not the monetary value.

number: When used by itself, it defaults to formatting the number to the locale’s format. When used in conjunction with the additional parameter fractionSize, it rounds the number to the number of places specified.{{product.inStock | number: 3}} will display 1000 as 1,000

Page 12: Internationalizing Your AngularJS App

Angular Translate

Page 13: Internationalizing Your AngularJS App

Angular TranslateModule that aids in i18n and l10n for

language, pluralization, and lazy loadingCan be used as a directive or filter (both in the

DOM and in the controller)Allows you to move i18n from the server to

the client

Page 14: Internationalizing Your AngularJS App

Setting up Angular TranslatePlugins: 1. angular-translate: Main plugin; contains the $translate service.2. angular-translate-loader-static-files: Helper plugin that allows

devs to specify a file name pattern for loading translation files, as well as the preferred language to fall back on.

3. angular-translate-loader-url: Helper plugin that allows for async/lazy loading.

4. angular-translate-partial-loader: Helper plugin that allows devs to load the translation files for only one module.

Page 15: Internationalizing Your AngularJS App

Setting up Angular Translate (cont.)Steps:

1. Download the source filesa. Download from Githubb. bower | npm install

2. Include the scripts in your page3. Inject Angular Translate as a dependency in the module(s) you want translated

angular.module(‘myI18nApp’, [‘ngLocale’, ‘tmh.dynamicLocale’, ‘pascalprecht.translate’]) 4. In your app’s configuration, if you’re using the static loader, inject the $translateProvider:

$translateProvider.useStaticFilesLoader({ prefix: '../languages/', suffix: '.json' });

Page 16: Internationalizing Your AngularJS App

Files for TranslationsShould be in JSON format

Multiple files for each locale

i.e., en-gb.json for the UK, en-us for the US, es-es for Spain, es-mx for Mexico, etc etc

Each file should be stored in a common folder, i.e., ‘locale’ or ‘languages’

Can name properties with a single word, or as ‘dot notation’ to designate sections:

{"navigation.dashboard": "Dashboard","navigation.appointments": "Appointments","navigation.addAppt": "Add New Appointment","navigation.addOneTimeAppt": "Add One Time Appointment","navigation.addRepeatingAppt": "Add Repeating Appointments","navigation.addTimeOff": "Add New Time Off",

....}

Page 17: Internationalizing Your AngularJS App

Inserting translations in your textCan be done several ways:

1. The translate filter<button>{{‘btn.close’ | translate}}</button>

2. The translate directive<button>

<span translate=“btn.close”>Close</span></button>

3. Using the translate filter in the controller

$translate('Home.calendar') .then(function(translatedValue){ $scope.mainTitle = translatedValue; })

Page 18: Internationalizing Your AngularJS App

Passing parameters to translated strings1. HTML:

<div><span translate=“Calendar.title” translate-values=“{‘date’:

calendar.defaultDate}”>Today’s date is {{calendar.defaultDate}}</span></div>

2. Interpolations of the variable in JSON:“Calendar.title”: “Today’s date is {{date}}”

Page 19: Internationalizing Your AngularJS App

Compiling translations with HTMLThere are cases where you can’t break a line for HTML changes (links, emphasis, etc) and keep it syntactically correct for all languages.

HTML:<span translate= “Text.withLink” translate-compile>

To learn more, <a href=“#”>view our documentation</a>.</span>

JSON:“Text.withLink”: “To learn more, <a href=‘#’>view our documentation.”

Page 20: Internationalizing Your AngularJS App

Making Locale Dynamic

Page 21: Internationalizing Your AngularJS App

Angular Dynamic LocaleAllows users to choose and change their localeAllows developers to pass in the browser’s locale (or

stored locale) and change it from the default locale if necessary

Changes the locale at app’s runtime, which allows you to use a stored locale

Modifies the $locale object so changing the locale will change all objects relying on the $locale service

Page 22: Internationalizing Your AngularJS App

Using Angular Dynamic Locale1. Install with bower | npm install angular-dynamic-locale2. Inject into your module: angular.module(‘myI18nApp’, [‘ngLocale’, ‘tmh.dynamicLocale’])3. In your app’s configuration, do:

app.config(["tmhDynamicLocaleProvider", function(tmhDynamicLocaleProvider){tmhDynamicLocaleProvider.localeLocationPattern(

'../bower_components/angular-i18n/angular-locale_{{locale}}.js');

tmhDynamicLocaleProvider.defaultLocale(language);

//Default languageif(language === 'es' || language === 'fr'){ //using this format so it won't try to pull in files that don't exist, like es-mx $translateProvider.use(language);} else { $translateProvider.preferredLanguage('en-us');};

}]);

Page 23: Internationalizing Your AngularJS App

Handling Calendars -- Angular UI Bootstrap Datepicker

Angular UI Bootstrap Datepicker: Built on top of the date filter so everything is localized. Settings include:starting-day

Adjustments through the controller, passed into the directive’s helper attributesHTML:

... <input type="text" class="form-control" datepicker-popup="shortDate" ng-model="dateObj.startDate" is-open="datepickers.start" datepicker-options="{{dateOptions}}" date-disabled="disabled(date, mode)" close-text="Close" ng-click="openDT($event, 'start')" />

…JS:

var firstDayOfWeek = $window.sessionStorage.getItem(‘firstDayOfWeek’);

$scope.dateOptions = {

'starting-day': firstDayOfWeek

};

Page 24: Internationalizing Your AngularJS App

Handling Calendars -- Angular UI CalendarAngular wrapper for fullCalendar. Has settings which include:

dayNames

dayNamesShort

monthNames

monthNamesShort

lang

firstDay

timeFormat

To adjust for i18n, in your HTML you need:<div ui-calendar="uiConfig.calendar" config="uiConfig.calendar" calendar="myCalendar"

class="calendar" ng-model="eventSources"></div>

And in your controller:var firstDayOfWeek = $window.sessionStorage.getItem(‘firstDayOfWeek’);

$scope.uiConfig = {

calendar:{

lang: currentLang,

firstDay: firstDayOfWeek,

...

}

};

Page 25: Internationalizing Your AngularJS App

Triggering Locale Changes on the Fly

Page 26: Internationalizing Your AngularJS App

Triggering locale change on directives

1. Use the $provide service and pass in the name of the directive to get the registered “map” for that directive

a. Providers expose the directive’s API app-wide and registers them with the injectorsb. Using the decorator method, we can intercept the creation of the directive on load.

2. Catches the $delegate (the original directive’s “map”, which can then be overwritten or monkey patched)

3. Set up listener on the directive’s scope on $localeChangeSuccess (this requires Angular Dynamic Locale)

4. Make modifications as needed (i.e., changing the first day of the week property on a calendar object)

5. Refresh the scope/alert the scope to the changesa. Call a method in the directive link (i.e., scope.move() )b. Use apply() to call the directive link with the modified scope and parameters:

originalLink.apply(this, arguments)

Page 27: Internationalizing Your AngularJS App

Triggering locale change on directives$provide.decorator('daterangeDirective', function($delegate, $compile, $parse, $translate, $rootScope) {

angular.forEach($delegate, function (directive) {

var originalCompile = directive.compile;

var originalLink = directive.link;

if (originalCompile) {

directive.compile = function () {

return function ($scope, $element, $attributes, ngModel) {

$scope.$on('$localeChangeSuccess', function () {

directive.link($scope, $element, $attributes, ngModel, $compile, $parse, $translate, $rootScope); //have to run the main fn on the directive b/c it will apply all the changes

});

originalLink.apply(this, arguments);

};

}

}

});

return $delegate;

});

Page 28: Internationalizing Your AngularJS App

Triggering locale change on Angular UI Calendar$provide.decorator('uiCalendarDirective', function($delegate, $locale, $rootScope, uiCalendarConfig) {

directive.compile = function () {

return function (scope, elm, attrs, controller) {

scope.$on('$localeChangeSuccess', function () {

uiCalendarConfig.dayNames = $locale.DATETIME_FORMATS.DAY;

uiCalendarConfig.dayNamesShort = $locale.DATETIME_FORMATS.SHORTDAY;

uiCalendarConfig.monthNames = $locale.DATETIME_FORMATS.MONTH;

uiCalendarConfig.monthNamesShort = $locale.DATETIME_FORMATS.SHORTMONTH;

uiCalendarConfig.lang = currentLang;

});

originalLink.apply(this, arguments); //This triggers the calendar to update on language change

};

}

}

});

Page 29: Internationalizing Your AngularJS App

Storing Locale

Page 30: Internationalizing Your AngularJS App

Methods of Storing Locale1. Session Storage: For temporary storage/only

detecting browser storage.2. Local Storage: For semi-permanent storage/only

detecting browser storage.3. Server Side: For permanent storage/when user

wants to see the app in his locale regardless of computer/browser used to signed in.

Page 31: Internationalizing Your AngularJS App

Changing languageHTML: <li><a href ng-click="changeLanguage('en-us', 0, account)" class="flag flag-us"></a></li>JS: $scope.changeLanguage = function(language, firstDayOfWeek, account){ account.locale = language;

account.firstDayOfWeek = firstDayOfWeek;

$translate.use(language);

tmhDynamicLocale.set(language);

$rootScope.$broadcast('firstDayOfWeekUpdated');

//Change language on server by updating the user account

accountData.updateAccount(accountId, account).then(function(data){

//Success ...

}, function(data){

//Error ...

})

};

Page 32: Internationalizing Your AngularJS App

Setting from Saved LocaleTo set the app to the locale saved on the server or sessionStorage, in controller:

//Fetch data from the server/sessionStorage first//Will default to English, thanks to the setup in app.configif($scope.account.locale !== null){ tmhDynamicLocale.set($scope.account.locale.toLowerCase());

$translate.use($scope.account.locale.toLowerCase());};

Page 33: Internationalizing Your AngularJS App

Wrapping Up

Page 34: Internationalizing Your AngularJS App

Food for ThoughtStart implementing i18n and l10n support early in developmentAs you build new pages, add translationsDetermine your app’s target markets/locales with business rulesMap out components and features that will need localization (I.e.,

calendars, date range pickers, timepickers, etc)Ask yourself how automated you want l10n to be -- i.e., browser

detection, users choosing which locale, etc

Page 35: Internationalizing Your AngularJS App

Q&AQuestions? Comments? Fire away!

Page 36: Internationalizing Your AngularJS App

ResourcesLinks:

Angular i18n guide: https://docs.angularjs.org/guide/i18nAngular Translate: https://angular-translate.github.io/

Angular Dynamic Locale: http://lgalfaso.github.io/angular-dynamic-locale/ W3C International: http://www.w3.org/International/

Scotch IO Tutorial: https://scotch.io/tutorials/internationalization-of-angularjs-applications

Reach out to me:email: [email protected]

Twitter: @SarahHudson2008