I have a HTML page containing several <div>
containers. I require to show these <div>
containers based on the user id. For example: I have 4 <div>
containers created in a page say div1, div2, div3 and div4. And I have two users: user1 and user2.
I would like to show div1 and div3 when user 1 access to the page. and show div2 and div4 when user2 access it. I would like to use ng-hide
and ng-show
directives of AngularJS. How can I achieve this?
I would set properties on the $scope in a user access object of some sort to toggle them whenever you load the user.
Assuming the user is loaded when the controller is it could be something like so:
app.controller('SecuredForm', function($scope) { //get your user from where ever. var user = getSomeUser(); // set your user permissions // here's some contrived example. $scope.permissions = { showAdmin: user.isRegistered && user.isAdmin, showBasic: user.isRegistered, showHelp: !user.isBanned } });
In your html you'd use those scope items to set show or hide your areas:
<div ng-show="permissions.showAdmin"> <h3>Admin Area</h3> <!-- admin stuff here --> </div> <div ng-show="permissions.showBasic"> <h3>Basic Info</h3> <!-- admin stuff here --> </div> <div ng-show="permissions.showHelp"> <h3>Help</h3> <!-- help stuff here --> </div>
One thing to note is that ng-show and ng-hide are simply not displaying the HTML... the html is still on the client. So be sure when you're making calls back to the server that require permissions to alter something you're checking them at the server. You can't assume the user has permission to do something just because the form was visible. (You probably already know this, I just want to be thorough).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With