如何在Angular JS控制器中翻译innerHTML文本?

时间:2014-12-29 06:22:37

标签: angularjs angularjs-directive

您好我正在开发一个支持两种语言(英语和意大利语)的Angular JS Web应用程序。到目前为止,我已经完成了我的html页面中的所有翻译,如下所示,它工作正常。

{{translation.ERROR_12}}

现在我需要从控制器传递一些文本,如下所示

case 'ERROR_12': document.getElementById("errorDiv").innerHTML= "Reporting error 12";
                break;

我的所有翻译都存储在.json文件中。如果案例匹配,那么我需要显示带翻译的相应消息。如果我像上面那样硬编码innerHTML文本,那么在非英语语言中它也会显示相同的文本。如何为上述代码申请翻译?所以我不在innerHTML中写下描述 我当之无愧的输出应该是这样的:

case 'ERROR_12': document.getElementById("errorDiv").innerHTML= $translate.ERROR_12;
                break;

1 个答案:

答案 0 :(得分:1)

对于HTML部分

<div ng-app>
<div ng-controller="TodoCtrl">
<div ng-click="callMeToSetErrorCode(1)" style="cursor:pointer">Click me to set error code1</div>
    <div ng-click="callMeToSetErrorCode(2)" style="cursor:pointer">Click me to set error code2</div>
    <div ng-click="callMeToSetErrorCode(3)" style="cursor:pointer">Click me to set error code3</div>

<div id="toShowError">
    {{ErrorToshow}}
</div>
</div>
</div>

控制器部分:控制器TodoCtrl function TodoCtrl($ scope,$ rootScope){     $ scope.allStatusInEng = {&#34; ERR_001&#34;:&#34;报告错误1&#34;,&#34; ERR_002&#34;:&#34;报告错误2&#34;,&#34; ERR_003&#34;:&#34;报告错误3&#34; };     $ scope.allStatusInItalian = {&#34; ERR_001&#34;:&#34;报告错误1 Italianno&#34;,&#34; ERR_002&#34;:&#34;报告错误2 Italianno&#34;,&# 34; ERR_003&#34;:&#34;报告错误3 Italianno&#34; };

alert("Helping Radha----");
$scope.ErrorToshow = "";
//If you know ,in which language in you need to show message you can set it as Default in a variable
    //For example if you are using Italian language

   // $scope.nameOfActivejson = "allStatusInItalian";
 $rootScope.nameOfActivejson = "allStatusInItalian";
$scope.callMeToSetErrorCode = function(){

    $scope.currentErrorCode = "ERR_001";
    $scope.callSwitchCase($scope.currentErrorCode);

  }
$scope.callMeToRevertLang = function(){
    $rootScope.nameOfActivejson ="allStatusInEng";
    alert("Ok done" +$rootScope.nameOfActivejson);

}
$scope.callSwitchCase = function(presentError){
    alert($rootScope.nameOfActivejson);
    alert(JSON.stringify($scope[$rootScope.nameOfActivejson]));
  switch (presentError) {
case 'ERR_001':
     $scope.ErrorToshow = $scope[$rootScope.nameOfActivejson]['ERR_001'];
    break;
case 'ERR_002':
   $scope.ErrorToshow = $scope[$rootScope.nameOfActivejson]['ERR_002'];
    break;
case 'ERR_003':
    $scope.ErrorToshow = $scope[$rootScope.nameOfActivejson]['ERR_003'];
    break;

}}

}