2016-11-08 45 views
0

我想通過用戶在其個人資料中具有的會話自動翻譯每個菜單標題的語言。我需要使用的方法是使用我們的PHP框架中的我們的API庫。將值從視圖動態地轉換爲範圍

在PHP中的一般用法,我們將使用此命令

$_lib->translate("wordToTranslate"); 

然後自動將的wordToTranslate詞翻譯成用戶的語言在他的個人資料/會話翻譯一個詞。

現在,由於我們使用的離子和AngularJS,我能做些什麼來實現這一目標是通過調用模板範圍:

<p>{{translatethis("wordToTranslate")}}</p> 

在控制我將有translatethis

 $scope.translatethis = function(arg) { 

     $http.post("http://example.com/API?Word=arg&Lang=1").success(function(response) { 
      console.log(response); 
     }); 
    } 
一個範圍

而且我得到這個錯誤

錯誤:10 $摘要()達到循環。

好像模板寫不完得到的<p>{{translatethis("wordToTranslate")}}</p>

實際輸出任何機構可以指導我如何清潔方法,請讓我避免了錯誤?

非常感謝提前

回答

0

問題1:您的翻譯請求不返回一個值,因此插值({{...}})無關插!

問題2:您的翻譯請求作出$http請求返回一個承諾,而不是實際值!這意味着你沒有內容可以插入。

我的建議是使詞的字典,並從那裏走。

舉個例子:

// Create some dictionaries 
$scope.translatedWords = {}; 
$scope.requestedWords = {}; 

$scope.translatethis = function(arg) { 
    if ($scope.translatedWords[arg]) { 
     // We have already translated this word, return it 
     return $scope.translatedWords[arg]; 
    } else { 
     if (!$scope.requestedWords[arg]) { 
      // We need to request the word 
      // Setting this stops us from making multiple requests while the request gets resolved. 
      $scope.requestedWords[arg] = true; 
      requestTranslation(arg); 
     } 
     return ''; 
    } 
} 

// Has no need to be on $scope as it's a private function 
function requestTranslation(arg) { 
    $http.post("http://example.com/API?Word=arg&Lang=1").success(function(response) { 
     console.log(response); 
     // Store the result of the translation into our map 
     $scope.translatedWords[arg] = response.data; 
    }); 
} 
+0

一些信息,我只是讀它,並且尚未進行測試。但對我來說看起來很美。你在Angular中看起來不錯。只有318?謝謝。 –

0

我的代碼有多個錯誤。

如果你使用一個函數,你需要有一個返回。

例如:

$scope.translatethis = function(arg) { 

return "my trad"; 
} 

但在你的情況,你需要這樣,你需要建立的東西asynchrone調用的API。

完成您的需求的最佳方法是使用角度翻譯等特定模塊。

如果你想開發一個自定義的解決方案,我認爲你需要了解更多關於異步函數,我建議你考慮$ filter實現,這對於這種類型的處理非常有用。

UPDATE:

如果您想對您模板只有一些變量保持這部分代碼就可以,例如地方:

<p>{{wordToTranslate}}</p> 

,改變你的函數類似這樣的

function translatethis(varToTranslate,arg) { 

    $http.post("http://example.com/API?Word=arg&Lang=1").success(function(response) { 
     console.log(response); 
varToTranslate = response.data 
    }); 
} 

並添加你的控制器像

translatethis($scope.wordToTranslate,"wordToTranslate"); 

但我認爲使用角度轉換更適合這種類型的需求。

+0

由於我使用的API,然後我需要的是有一個與POST/GET方法asynchronelly的東西,那就是在問題的問題。 –

+0

我加上之前的響應 – qchap