【发布时间】:2018-12-20 12:31:41
【问题描述】:
我正在尝试从 AngularJS 应用程序的 html 页面中的服务器获取一些信息。但是,当我使用 $scope 在我的 html 文件中调用该函数时,该方法本身工作正常。我收到 $rootScope:infidg 错误。
控制器中的方法:
$scope.getTranslation = function(){
$http.get('https://producthero.com/index.php?option=com_hero&task=language.translate&s=SEARCH')
.then(
function (response) {
return response.data.translation;
}
);
};
使用 ng-app 和 ng-controller 调用 html 文件:
<div ng-controller="Product">
<span>{{getTranslation()}}</span>
</div>
我使用这种翻译方式是因为网站的初始后端是在 Joomla 中运行的,我知道 i18n,但我们不能在这里使用它。
错误是:
http://errors.angularjs.org/1.6.4/$rootScope/infdig?p0=10&p1=%5B%5D
angular.min.js:123 Error: [$rootScope:infdig] <http://errors.angularjs.org/1.6.4/$rootScope/infdig?p0=10&p1=%5B%5D> at angular.min.js:6 at m.$digest (angular.min.js:147) at m.$apply (angular.min.js:149) at angular.min.js:21 at Object.invoke (angular.min.js:44) at c (angular.min.js:21) at Sc (angular.min.js:22) at ue (angular.min.js:20) at HTMLDocument.<anonymous> (angular.min.js:331) at i (jquery.min.js:2)
我希望这只是我的愚蠢,我错过了一些东西来使这种通过 http 直接调用成为可能!
编辑:
我的翻译问题的解决方案如下(感谢@Aleksey Solovey 的回答):
控制器方法
$scope.translations = {};
$scope.getTranslation = function(string){
$http.get('https://producthero.com/index.php?option=com_hero&task=language.translate&s=' + string)
.then(
function (response) {
$scope.translations[string] = response.data.translation;
});
};
查看通话
<div ng-app="products">
<div ng-controller="Product">
<span ng-init="getTranslation('SEARCH')">{{translations.SEARCH}}</span>
</div>
</div>
【问题讨论】:
-
ng-init指令可能会被滥用以在模板中添加不必要的逻辑量。ngInit只有少数合适的用法。见AngularJS ng-init API Reference。
标签: angularjs angularjs-scope angularjs-http