lang-switcher.directive.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. (function() {
  2. 'use strict';
  3. app.directive('langSwitcher', langSwitcherController);
  4. function getCurrentlanguage(key) {
  5. return this.languages.filter((function(item) { return item.key === key }))[0];
  6. }
  7. function langSwitcherController() {
  8. return {
  9. restrict: 'E',
  10. templateUrl: './app/directives/lang-switcher/lang-switcher.template.html',
  11. scope: {},
  12. link: function(scope, element, attr) {},
  13. controller: ['$scope', '$translate', '$rootScope', function($scope, $translate, $rootScope) {
  14. $scope.languages = [
  15. { key: 'en', value: 'En' },
  16. { key: 'ru', value: 'Ru' },
  17. { key: 'ua', value: 'Ua' }
  18. ];
  19. $scope.showMenu = false;
  20. $scope.toggleMenu = function() {
  21. $scope.showMenu = !$scope.showMenu;
  22. }
  23. var key = localStorage.getItem('preferredLanguage') || 'en';
  24. $scope.currentLang = getCurrentlanguage.call($scope, key);
  25. $scope.changeLanguage = function(key) {
  26. $scope.currentLang = getCurrentlanguage.call($scope, key);
  27. $translate.use(key);
  28. localStorage.setItem('preferredLanguage', key);
  29. $rootScope.$broadcast('changeLang', key);
  30. $scope.showMenu = !$scope.showMenu;
  31. };
  32. $scope.$on('changeLang', function(event, value) {
  33. if ($scope.currentLang.key !== value) {
  34. $scope.currentLang = getCurrentlanguage.call($scope, value);
  35. }
  36. });
  37. }],
  38. }
  39. }
  40. langSwitcherController.$inject = [];
  41. })();