我想通过用户在其配置文件中的会话自动翻译视图中每个菜单标题的语言。我需要使用的方法是使用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>
的真实输出
有没有人可以指导我如何清洁这个方法,以便我避免错误?
提前致谢
问题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;
});
}
您的代码中有多个错误。
如果你想使用一个函数,你需要有一个返回值。
的例子:
$scope.translatethis = function(arg) {
return "my trad";
}
但是在你的情况下,你需要调用api,所以你需要构建一些异步的东西。
最好的方法是使用一些特定的模块,比如angular-translate。
如果你想开发一个自定义的解决方案,我认为你需要学习更多关于异步函数的知识,我建议你考虑$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");
但是我认为对于这种类型的需求,使用角转换更好。