パッケージをインストール
1 2 3 4 5 |
$ npm install angular-translate $ npm install angular-translate-storage-cookie $ npm install angular-translate-storage-local $ npm install angular-translate-loader-static-files $ npm install angular-translate-handler-log |
HTML
1 2 3 |
<md-select ng-model="selectedLanguage" ng-model-options="{trackBy: '$value.id'}" ng-change="setSelectedLanguage(selectedLanguage);" style="font-size: 15px;"> <md-option ng-value="language" ng-repeat="language in languages">{{ language.name }}</md-option> </md-select> |
AngularJS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
(function () { 'use strict'; angular.module('mean.meanStarter', ['ngMaterial', 'pascalprecht.translate']) .controller('StarterController', StarterController) .config(['$translateProvider', function($translateProvider) { // デフォルトは、ブラウザの言語設定に依存する var selectedLanguage = $translateProvider.resolveClientLocale().substr(0,2); // クッキーが設定されている場合は、クッキーの言語にする var $cookies; angular.injector(['ngCookies']).invoke(['$cookies', function(_$cookies_) { $cookies = _$cookies_; }]); $translateProvider.useStaticFilesLoader({ prefix: '/meanStarter/assets/i18n/locale-', suffix: '.json' }); if($cookies.get('selectedLanguage')) { selectedLanguage = $cookies.get('selectedLanguage'); } $translateProvider.preferredLanguage(selectedLanguage); $translateProvider.fallbackLanguage('en'); $translateProvider.useMissingTranslationHandlerLog(); $translateProvider.useLocalStorage(); $translateProvider.use(selectedLanguage); }]); StarterController.$inject = ['$scope', 'Global', '$translate', '$cookies']; function StarterController ($scope, Global, $translate, $cookies) { $scope.global = Global; $scope.package = { name: 'meanStarter' }; // 言語の切り替え $scope.languages = [ { id: 'en', name: 'ENGLISH' }, { id: 'ja', name: '日本語' } ]; // 言語選択でデフォルトセット $scope.selectedLanguage = { id: 'en', name: 'ENGLISH' }; if($cookies.get('selectedLanguage')) { angular.forEach($scope.languages, function(val, key) { if($translate.proposedLanguage() == val.id) { $scope.selectedLanguage = val; } }) } // 言語の切り替えをクッキーに反映させる $scope.setSelectedLanguage = function(selectedLanguage) { var dayForCookies = new Date(); // 365日間は言語設定のクッキーを保持 dayForCookies.setDate(dayForCookies.getDate() + 365); var cookiesOption = {expires: dayForCookies, path: '/'}; $cookies.put('selectedLanguage', selectedLanguage.id, cookiesOption); $translate.use(selectedLanguage.id); }; } })(); |