使用$digest的无限循环

Infinite loop with $digest angularJS

本文关键字:无限循环 digest 使用      更新时间:2023-09-26

我有一个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) 

我的控制器中没有任何监视器。发生什么事情了?

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

如果你解耦了隐藏和数据获取,这应该是预期的工作