$ digest angularJS的无限循环

时间:2014-08-13 10:25:59

标签: javascript angularjs

我有一个带有angularjs $ q和promise的无限循环。 这是代码:

<a ng-hide="!isTechnician()" class="pull-right" href="#/admin/techniciansState"><span
                                        class="glyphicon glyphicon-map-marker"></span>&nbsp; Estado del técnico &nbsp;
                                </a>

这是js代码:

$scope.isTechnician = function () {
        if (!$scope.notCheckTechnician) {
            SecurityService.getCurrentUser().then(function (user) {
                if ($.inArray('technician', user.roles)) {
                    return true;
                } else {
                    return false;
                }
            });
        }

    };

 var SecurityService = function($resource, $q, $rootScope, API_URL) {
     // Definición del servicio REST
     var Security = $resource(API_URL + '/security/:action', {
         action: "@action"
     }, {
         'currentUser': {
             method: 'GET',
             isArray: true,
             params: {
                 action: 'current-user'
             }
         }};
var getCurrentUser = function() {
             var deferred = $q.defer();
             var user = Security.currentUser(function() {
                 if (user.length > 0) {
                     _setCurrentUser(user[0]);
                     deferred.resolve(user[0]);
                 } else {
                     _setCurrentUser(null);
                     deferred.reject('Not authenticated');
                 }
             }, function() {
                 _setCurrentUser(null);
                 deferred.reject('Not authenticated');
             });
             return deferred.promise;
         };

错误:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.2.18/$rootScope/infdig?p0=10&p1=%5B%5D
    at http://localhost:900/bower_components/angular/angular.js:78:12
    at Scope.$get.Scope.$digest (http://localhost:900/bower_components/angular/angular.js:12434:19)
    at Scope.ng.config.$provide.decorator.$delegate.__proto__.$digest (<anonymous>:844:31)
    at Scope.$get.Scope.$apply (http://localhost:900/bower_components/angular/angular.js:12660:24)
    at Scope.ng.config.$provide.decorator.$delegate.__proto__.$apply (<anonymous>:855:30)
    at done (http://localhost:900/bower_components/angular/angular.js:8272:45)
    at completeRequest (http://localhost:900/bower_components/angular/angular.js:8477:7)
    at XMLHttpRequest.xhr.onreadystatechange (http://localhost:900/bower_components/angular/angular.js:8416:11) 

我的控制器中没有任何观察者。发生了什么事?

1 个答案:

答案 0 :(得分:1)

在每个$ digest循环中执行ng-hide个表达式。在ng-hide表达式的函数中,您将从数据库中提取数据,从而触发$ digest。这会导致无限$ digest循环。

如果您取消隐藏和数据提取,这应该按预期工作。