1

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.

Mike Sav
  • 14,805
  • 31
  • 98
  • 143
  • possible duplicate of [Infinite loop with Angular expression binding](http://stackoverflow.com/questions/17466872/infinite-loop-with-angular-expression-binding) – Stewie Nov 04 '13 at 19:42

1 Answers1

1

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)

Kos Prov
  • 4,207
  • 1
  • 18
  • 14
  • Just keep in mind that Angular 1.2+ forbids direct binding of promises in templates. Start `$scope.isSuperUser` to `false` and update it with the actual result on a `then()` success callback. – Kos Prov Aug 26 '15 at 08:01