ses
ses

Reputation: 13342

Permission directive in AngularJS

Let's say I want to have a directive that checks permission. So that I coud do this:

<a permissions="something.delete">Delete</a>

If "something.delete" in the list of allowed permissions then nothing is rendered.

Having this code:

link: function (scope, element, attrs) {
   var permissionsPromise = PermissionService.checkForPermissions(attrs.permissions);

   permissionsPromise.then(function(result) {
     if (result=== false) {
        element.remove();
     }
  })
}

But because PermissionService.checkForPermissions() returns promise, so it may take some time to figure out the permissions, meanwhile link function will render the a-element before knowing the result of permission-check.

What would be the proper solution to fix that issue?

Upvotes: 0

Views: 510

Answers (1)

mccainz
mccainz

Reputation: 3497

Reverse your logic and hide the element by default and then show it based on the promise value.

something along the lines of elem[0].style.display = 'none' -> elem[0].style.display = 'block'

Ask yourself what is your real goal, as you aren't really implementing permissions checking on the client-side (or you shouldn't be). This should be more to provide the user with the correct UI experience. If you want to remove it altogether then just keep a reference to the parent element, remove the element, and when your promise returns append it back to the parent .. or not.

Upvotes: 2

Related Questions