JSFiddle - React, Tailwind, and code Playground
HTML
<body ng-app="myApp" ng-controller="MainController" >
<p><language key="hello-world"></language></p>
<label>
<language message="myLabel"></language>:
<input placeholder-language language-key="username" />
</label>
</body>
JavaScript
var app = angular.module("myApp", []);
app.controller('MainController', ['$scope', 'Language', function($scope, Language) {
$scope.myLabel = "username";
}]);
app.factory('Language', function() {
var languageFile = {
"es" : {
"hello-world" : "Hola, mundo!",
"username" : "Nombre de usuario"
},
"en" : {
"hello-world" : "Hello, world!",
"username" : "User name"
}
};
var defaultLanguage = "es";
var currentLanguage = "es";
function get(key, language) {
try {
return languageFile[getCurrentLanguage(language)][key];
} catch(e) {
return "Unknown text";
}
};
function getCurrentLanguage(language) {
try {
if (language) {
if (languageFile[language]) {
currentLanguage = language;
} else {
return defaultLanguage;
}
}
} catch(e) {
}
return currentLanguage;
}
function setLanguage(language) {
if (language) {
currentLanguage = language;
}
};
function getLanguage() {
return currentLanguage;
};
// PUBLIC METHODS DEFINITION
return {
get : get,
getLanguage : getLanguage,
setLanguage : setLanguage
};
});
app.directive("language", ['Language', function(Language) {
return {
restrict : 'E',
scope : {
key : "@",
message : "="
},
link : function(scope, element, attrs) {
var text = "";
if (scope.key) {
text = Language.get(scope.key);
} else if (scope.message) {
text = Language.get(scope.message);
}
element.replaceWith(text);
}
};
}]);
app.directive("placeholderLanguage", ['Language', function(Language) {
return {
restrict : 'A',
scope : {
key : "@languageKey",
message : "=languageMessage"
},
link : function(scope, element, attrs) {
var text = "";
if (scope.key) {
text = Language.get(scope.key);
} else if (scope.message) {
text = Language.get(scope.message);
}
if (text != "") {
attrs.$set('placeholder', text);
}
}
};
}]);