nmrg8g
Last Updated: February 25, 2016
·
2.911K
· lukasz-madon
B2bc42f69510d6a1d2c9cde1c2214d24

Permissions directive to show elements depending in access rights in angularjs

This is an angular directive that shows elements depending on user access privilege

 //ls is loginService
angular.module('app.directives')
.directive('accessLevel', function() {
  return {
    restrict: 'A',
    link: function($scope, element, attrs) {
      var prevDisp = element.css('display')
      , currUserRole
      , accessLevel;

      $scope.$watch('ls', function(ls) {
        currUserRole = ls.userRole;
        updateCSS();
      }, true);

      attrs.$observe('accessLevel', function(al) {
        if(al) {
          accessLevel = accessLevels[al];
        }
        updateCSS();
      });

      function updateCSS() {
        if(currUserRole && accessLevel) {
          if($scope.ls.hasAccess(accessLevel, currUserRole)) {
            element.css('display', prevDisp);
          }
          else {
            element.css('display', 'none');
          }
        }
      }

    }
  };
});

Remember, this is just for UX not a security feature. Have a proper check serverside.

Say Thanks
Respond