从视图到范围动态转换值

al_kasih_empatix

我想通过用户个人资料中的会话来自动翻译视图中每个菜单标题的语言。我需要使用的方法是使用我们在php框架中拥有的API库。

在php的一般用法中,我们将使用此命令来翻译单词

   $_lib->translate("wordToTranslate"); 

然后,它将自动将单词翻译wordToTranslate成用户在其个人资料/会话中使用的语言。

现在,由于我们正在使用IONIC和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次$ digest()迭代。

似乎模板永远无法完成,无法获得 <p>{{translatethis("wordToTranslate")}}</p>

请问任何人可以指导我如何清洁此方法,以免发生错误吗?

提前谢谢了

西蒙·K

问题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;
    });
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章