我正试图在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应用程序和ng控制器调用html文件:
<div ng-controller="Product">
<span>{{getTranslation()}}</span>
</div>
我使用这种翻译方式是因为网站的初始后端运行在Joomla中,我知道i18n,但我们不能在这里使用它。
错误为:
http://errors.angularjs.org/1.6.4/$rootScope/indig?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>
$http
请求将返回Promise,而不是某个值。因此,您需要首先填充一个作用域变量,然后(异步(使用它。以下是它应该是什么样子:
var app = angular.module('myApp', []);
app.controller('Product', function($scope, $http) {
$scope.getTranslation = function() {
$http.get('https://producthero.com/index.php?option=com_hero&task=language.translate&s=SEARCH').
then(function(response) {
$scope.translation = response.data.translation;
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Product">
<span ng-init="getTranslation()">{{translation}}</span>
</div>
</div>
您能在不使用ng init的情况下给出一个不同的答案来提供一个例子吗?
只需在控制器中手动初始化即可:
app.controller('Product', function($scope, $http) {
$scope.getTranslation = function() {
$http.get('https://producthero.com/index.php?option=com_hero&task=language.translate&s=SEARCH').
then(function(response) {
$scope.translation = response.data.translation;
});
};
//INSTEAD OF ng-init
$scope.getTranslation();
});
<div ng-app="myApp">
<div ng-controller="Product">
̶<̶s̶p̶a̶n̶ ̶n̶g̶-̶i̶n̶i̶t̶=̶"̶g̶e̶t̶T̶r̶a̶n̶s̶l̶a̶t̶i̶o̶n̶(̶)̶"̶>̶{̶{̶t̶r̶a̶n̶s̶l̶a̶t̶i̶o̶n̶}̶}̶<̶/̶s̶p̶a̶n̶>̶
<span>{{translation}}</span>
</div>
</div>
ng-init
指令可能会被滥用,从而在模板中添加不必要的逻辑量。ngInit只有几种适当的用法。请参阅AngularJS ng-init API参考。
出于性能原因,应避免在带有{{ }}
的HTML插值绑定中使用函数。这些函数在每个摘要循环中被调用一次或多次。
错误
<div ng-controller="Product"> <span>{{getTranslation()}}</span> </div>
返回promise的异步函数将导致无限的摘要错误。
有关更多信息,请参阅
- AngularJS错误参考-$rootScope:infdig无限$digest循环