将值从视图动态转换为范围

时间:2016-11-08 22:05:48

标签: angularjs ionic-framework

我想通过用户在其个人资料中拥有的会话自动翻译每个菜单标题的语言。我需要使用的方法是使用我们在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>

的实际输出

请问任何人都可以指导我如何清理此方法,以便我避免错误?

非常感谢提前

2 个答案:

答案 0 :(得分:0)

您的代码有多处错误。

如果您使用某个功能,则需要返回。

示例:

$scope.translatethis = function(arg) {

return "my trad";
 }

但是在你的情况下你需要调用api所以你需要构建一些asynchrone。

完成您需求的最佳方法是使用角度转换等特定模块。

如果您想开发自定义解决方案,我认为您需要了解有关异步功能的更多信息,我建议您考虑$ filter实现,这对于此类处理非常有用。

更新:

如果你想保留这部分代码,你可以在模板上只放置一些变量:

   <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");

但我觉得使用角度转换可以满足这类需求。

答案 1 :(得分: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;
    });
}