I am trying to write directive that will evaluate user permissions.
In case user is not permitted to see given content
the content will not be displayed (done, working fine)
requests from controllers inside permission directive will not get fired.
Example:
Controller:
function MyController ($scope){
// performing imediately server request, witch is allowed only for admin
// therefore i will get error when non admin user access this page
}
Permission directive:
return {
priority: 1000,
restrict: 'E',
link: (scope, element, attrs) => {
var permission = attrs.permission;
if (/*evaluating permission*/) {
// user has permission, no work for me
return;
}
element.remove();
}
};
All together:
<permission permission="isAdmin">
<div ng-controller="MyController">
</div>
</permission>
This version is removing elements from DOM, but request in MyController still gets executed. Off course, I can make check for permissions in MyController, but I don't want to.
Thank for help.
Your issue is that the controller will always be called before the link function executes. See this fiddle.
function MyCtrl($scope) {
console.log('in controller');
}
myApp.directive('permission', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
console.log('in link');
Log shows:
in controller
in link
I tried another approach and put removal of element into compile function. According to log, it is executed BEFORE controller, so it is right place. Anyway the request was still fired. So I tried just as a blind shot remove element children (I know, it does not make sense, removal of element should be sufficient and should remove children also).
But it worked!
compile: function(element) {
var children = element.children();
children.remove(); element.remove();
}
It is working, but I am not sure how much OK it is (e.g. future version Ang.)
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