Reputation: 15291
I need to check the status of a user in my AngularJS app to show specific functionality content. In my view I have the following HTML:
<span ng-show="authService.isSuperUser()">You are a Super User</span>
To determine if the user has "superuser" status and display the span I have the following JavaScript code in my service
this.isSuperUser = function () {
if (loggedInUser !== null) { // loggedInUser is true in most cases
return getSuperUser();
} else {
return false;
}
};
var getSuperUser = function(){
return $http({method: 'GET', url: '/url/to/rest/service/for/superuser' }).then(function (response) {
return response; // this is either true or false and is working
}, function () {
console.log('Yikes! An Error!');
return false;
});
};
Now the getSuperUser
function provides the correct result (either true or false) however when I run this in the browser I generate thousands of Infinite $digest Loop errors. I'm obviously going about this the wrong way, any ideas on how I can best implement my solution and stop producing the errors? The HTML view is loaded when a user goes to a specific URL like myapp.com/#/youraccount and the ng-show="authService.isSuperUser()"
is not loaded before in the app.
Upvotes: 1
Views: 286
Reputation: 4293
try this code:
.factory('authService', function($http) {
return {
isSuperUser: function () {
return $http.get(......);
}
};
})
.controller('MyCtrl', function($scope, authService) {
$scope.isSuperUser = authService.isSuperUser();
})
<span ng-show="isSuperUser">you are a super user</span>
when your controller runs it calls the service which initiates an ajax call and immediately returns a promise.
you copy that promise to a $scope variable named isSuperUser.
your view binds to that promise. when it gets resolved it will either be true or false and ng-show will function accordingly. until then it is considered false (i suppose :P)
Upvotes: 1