Question

table view

In this application there are columns on a table with corresponding buttons to 'EDIT' or 'DELETE'. On some of the views there are 6 or 7 instances of these columns. I know with AngularJS, I shouldn't be thinking of how to manipulate with jQuery. However, with this instance of needing to show/hide numerous items based on user role is it more efficient to use a directive or a line or two of jQuery to addClass() for the specific items?

With AngularJS, I'd need to write the directive then apply it on the HTML for the items and with jQuery I'd write a line or two on the backend JS and go add some ID's or sprinkle in a class for these items.

Was it helpful?

Solution

I had the same requirement and went for a directive solution. This works well for me, is fully reusable and flexible. Sharing it here if this helps you or others (This was inspired by some article that I read on the web and cannot recall any longer...Apologies to their authors). Plus since my app is written with angularJS and it is cleaner as it does not mix AngularJS and JQuery code.

The directive is called has-permission and is used as follows:

<i class="btn btn-default btn-sm" ng-click="clickAction()" has-permission="Edit"><span class="glyphicon glyphicon-edit" title="Edit"></span></i>

The directive code itself is pretty simple:

myDirectives.directive('hasPermission', ['permissionsService', function (permissionsService, permissions) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var value = attrs.hasPermission.trim();
            var notPermissionFlag = value[0] === '!';
            if (notPermissionFlag) {
                value = value.slice(1).trim();
            }

            function toggleVisibilityBasedOnPermission() {
                var hasPermission = permissionsService.hasPermission(value);

                if (hasPermission && !notPermissionFlag || !hasPermission && notPermissionFlag)
                    element.show();
                else
                    element.hide();
            }
            toggleVisibilityBasedOnPermission();
            scope.$on('permissionsChanged', toggleVisibilityBasedOnPermission);
        }
    };
}]);

The permissionsService is a service that holds the current user permission. This is set during the login process.

As mentionned by Ben Felda, anything you do on the client side is only for improved user experience. The actions/resources associated with the buttons must be checked for permission on the server side too.

PS: I am not sure about whether there is any performance advantage/disadvantage over a JQuery solution, but this works like a charm for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top