0

I am a beginner with AngularJS and Im facing the following problem:

I have a screen with a side-nav that every link is managed by AngularJS' router. The point is that some options from the side-nav as well as some content will be only displayed to some special kind of users, lets called them Admins.

I want to use something like:

<ng-if="isAdmin == true">
  ....
</ng-if>

so the question is how I set isAdmin variable with a value that is coming from the request?

Juan BC
  • 176
  • 2
  • 8

1 Answers1

1

I am not familiar with Spring, but you can for example make an Angular $http request to Spring to ask if the user is an admin, and let it send back true or false, and set the result of the response in the controller. Like this:

var url = 'someUrl'; // URL to the spring framework that responds with a JSON type
                     // response containing { isAdmin: true } or { isAdmin: false }
$http.get(url).success(function(response) {
    $scope.isAdmin = response.data.isAdmin;
});

Edit:

Alternatively, you can set a global variable in JavaScript, for example somewhere in <head> and put it on the $rootScope. I don't know exactly how to do this with Spring, but the HTML must look something like this:

<script>
var isAdmin = true; // or false
</script>

Then, you have access to this variable everywhere, so you can put it on the $rootScope in your main controller:

$rootScope.isAdmin = isAdmin;

Then, you have access to it in all views.

Jeroen Noten
  • 3,574
  • 1
  • 17
  • 25
  • maybe want to add the request to a service and then call the service on the controller. But yeah this is one way for doing what you have asked for. – rdk1992 Jul 29 '14 at 16:08
  • Yes, i was considering that option, the point is that is a variable that im gonna use almost in every URL managed by the router so i was figuring out if i can do it without calling that RESTservice so often, maybe i should set it up in RootScope ? – Juan BC Jul 29 '14 at 16:34
  • I don't know how it works with Spring, but you can probably set it as a global variable somewhere in the of the page, and then put int on `$rootScope` indeed. I'll update my answer. – Jeroen Noten Jul 29 '14 at 17:10
  • You could think on making a factory for all this global variables, this may not be the only one you end up needing, and having a – rdk1992 Jul 29 '14 at 19:51
  • Making a factory for only storing global data is OK, but I would not recommend it. Don't write more code than necessary. Read the very last sentence of the very last AngularJS FAQ item: https://docs.angularjs.org/misc/faq – Jeroen Noten Jul 29 '14 at 20:24
  • I like the idea of creating this factory for global variables, i think it fits the solution i want, because the first thing i load is the side-nav and the it is not needed to be changed anymore this side-nav so it can store this boolean variable during the user interaction. Thank guys for the cool ideas exposed!! – Juan BC Jul 29 '14 at 21:32