javascript - How to convert website into multi language using AngularJs -
my approach translating 1 time when applied on element on angular template when applied multiple directive template making multiple time api call how avoid it. solution please comment
var directive = { restrict: 'ae', scope: false, multielement: true, link: link }; $rootscope.cityname = cookieservice.getcookie('lang'); $rootscope.translatethese = []; $rootscope.translationdata = ''; $rootscope.translationcounter = 0; function link(scope, element, attr) { scope.$evalasync(function() { $rootscope.translatethese.push(element[0]); scope.$on('translateapisuccess', function(e, data) { angular.foreach($rootscope.translatethese, function(elem) { var translatedstring = $rootscope.translationdata[elem.innerhtml.trim().tolowercase()]; elem.innerhtml = translatedstring; // $compile(element.contents())(scope); }) }) }); // 0 second timeout push execution of // directive next digest cycle dynamic values // present. can use scope.$evalsync purpose. // // @example // $timeout(function() { // $timeout(function() { // use scope.$watch here watching $viewcontentloaded // scope.$watch('$viewcontentloaded', function(e, u) { $rootscope.translationcounter++; var translatethese = []; // if (scope.$last === true && scope.translationcounter === $rootscope.translatethese.length) { //we can use scope.$last isn't working if ($rootscope.translationcounter === $rootscope.translatethese.length) { $rootscope.translatethese.foreach(function(sentence) { // trim.apply(sentence).split(" ").foreach(function(v) { translatethese.push(sentence.innerhtml.replace(/[^a-za-z ]/g, "")); // }) }) dataservice.statictranslation('guj', translatethese).then(function (response) { $rootscope.translationdata = response.response; scope.$emit('translateapisuccess', response.response); // when using translateapi horizontal // $rootscope.translationdata = json.parse(response.response).staticlangtranslationapplicationresponse.staticlangtranslationapplication.translations; // scope.$emit('translateapisuccess', json.parse(response.response).staticlangtranslationapplicationresponse.staticlangtranslationapplication.translations); }); } }); } return directive; }
you @ using angular translate service: https://github.com/angular-translate/angular-translate
it offers filter, directive , service translating content.
Comments
Post a Comment