Skip to content
Advertisement

How i show/hide a button in angular according to user authorization?

I have tried something like this

 <button ng-if="!isAuthenticated()" ng-click="deleteReview()">Delete</button>

And in my javascript

  $scope.isAuthenticated = function() {
                $http.get("api/user/getAuthenticatedUser")
                    .success(function(user) {
                        if (user != null) {
                            return true;
                        }
                        return false;
                    });
            }

But it return me some errors at $ rootscope

Advertisement

Answer

Better use $http service provided by angular. Set authentication variable as false, call the authentication service from backend and change the value of authentication variable. Binding from Angular will transmit the value to the view and you will be able to use the value in view.

   $scope.isAuthenticated = false; // init as false

// make the method that checks autentication
$scope.checkAuth = function() {
    $http({
      method: 'GET',
      url: 'api/user/getAuthenticatedUser'
    }).then(function successCallback(user) {
        if (user != null) {
            $scope.isAuthenticated = true;
        } else {
            $scope.isAuthenticated = false;
        }

      }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });

}


// call the autentication method
$scope.checkAuth();

HTML:

<button ng-if="!isAuthenticated" ng-click="deleteReview()">Delete</button>
Advertisement