/angularjs/

AngularJS - Translate Example

2014-11-01 23:17:26

GitHub

app.js

var app = angular.module('transTest', ['pascalprecht.translate']);

app.config(['$translateProvider', function ($translateProvider) {

    translate.forEach(function (item) {
        var key = Object.keys(item).toString();
        var arr = item[key];
        $translateProvider.translations(key, arr);
    });

    $translateProvider.preferredLanguage('en');
}]);

app.controller('LanguageSwitcherCtrl', function ($scope, $translate) {
    $scope.changeLanguage = function (key) {
        $translate.use(key);
    };
});

app.controller('TestCtrl', function ($scope) {
    $scope.title = 'TITLE';
    $scope.foo = 'FOO';
});

translate.js

var translate = [
    {
        'en': {
            'TITLE': 'Hello',
            'SUB_TITLE': 'Hello 2',
            'SUB.SUB.TITLE': 'Hello 3',
            'FOO': 'This is a paragraph'
        }
    },
    {
        'pl': {
            'TITLE': 'Czesc',
            'SUB_TITLE': 'Czesc 2',
            'SUB.SUB.TITLE': 'Czesc 3',
            'FOO': 'To jest paragraf'
        }
    },
    {
        'cs': {
            'TITLE': 'Ahoj',
            'SUB_TITLE': 'Ahoj 2',
            'SUB.SUB.TITLE': 'Ahoj 3',
            'FOO': 'Toto je odstavec'
        }
    }
]

index.html

<!DOCTYPE html>

<html>
<head lang='"en"'>
<meta charset="utf-8"/>
<title>AngularJS-Translate Example</title>
<script src='"bower_components/angular/angular.min.js"'></script>
<script src='"bower_components/angular-translate/angular-translate.min.js"'></script>
<script src='"translate.js"'></script>
<script src='"app.js"'></script>
<link href='"bower_components/bootstrap/dist/css/bootstrap.min.css"' rel='"stylesheet"'/>
<style>
        .margin-box {
            margin-top: 25px
        }
    </style>
</head>
<body ng-app='"transTest"'>
<div class='"container"'>
<section class='"btn-group' margin-box&quot;="" ng-controller='"LanguageSwitcherCtrl"'>
<button autofocus='"true"' btn-success&quot;="" class='"btn' ng-click="&quot;changeLanguage('en')&quot;">english</button>
<button btn-success&quot;="" class='"btn' ng-click="&quot;changeLanguage('pl')&quot;">polish</button>
<button btn-success&quot;="" class='"btn' ng-click="&quot;changeLanguage('cs')&quot;">čeština</button>
</section>
<section class='"well' margin-box&quot;="" ng-controller='"TestCtrl"'>
<h1>{{ title | translate }}</h1>
<h2>{{ "SUB_TITLE" | translate }}</h2>
<h3>{{ "SUB.SUB.TITLE" | translate }}</h3>
<p>{{ foo | translate }}</p>
</section>
</div>
</body>
</html>