I understand the concept of the infinite digest loop and how it occurs, but I am encountering an issue. You can see my code and problem demonstrated in this fiddle:
If you check the console in the jsfiddle, you'll notice the infinite digest loop.
The crux of the issue is that I need to make decisions based on data that may not have loaded yet, so I have to wait for the promise to resolve using then(). I have a promise named user, on which I call then() in two different places in the code.
- Right after I define it, in order to set a scope variable based on it.
- In another scope method called $scope.isAdmin()
Regarding the second point, one might wonder why I don't simply use $scope.user directly within the $scope.isAdmin() method. The reason is that there's a possibility for $scope.isAdmin() to be invoked before the async request for the user completes, necessitating a 'block' before returning from $scope.isAdmin().
So, my question is: what aspect of $scope.isAdmin() makes Angular perceive that a 'watched' variable has changed and triggers the digest cycle?
After all, $scope.isAdmin() itself does not alter anything.
Here is the simplified code snippet:
HTML:
<body ng-controller='myController'>
<div ng-if='isAdmin()'>Hi! <strong>{{ user.username }}</strong> is an Admin!!!</div>
<div ng-if='!isAdmin()'>Hi! <strong>{{ user.username }}</strong> is NOT an Admin!!!</div>
</body>
And the JavaScript:
angular.module('myApp', [])
.factory('myService', function($q, $timeout) {
return {
getUser: function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve({ username: 'me', isAdmin: true });
}, 2000);
return deferred.promise;
}
};
})
.controller('myController', function($scope, $q, myService) {
var getUserDeferred = $q.defer();
var user = getUserDeferred.promise;
user.then(function(user) {
$scope.user = user;
return user;
});
$scope.getUser = function() {
return myService.getUser().then(function(user) {
getUserDeferred.resolve(user);
});
};
$scope.isAdmin = function() {
return user.then(function(user) {
return user.isAdmin;
});
};
$scope.getUser();
});