Reputation: 1940
I'd like to have a global permission check for certain elements in my markup, but I don't necessarily want/need to have my controller be aware of it. The permission check itself is quite arbitrary, as the back-end services will block any unauthorised access... this is just for hiding/disabling controls.
Essentially, I have a permission service which will check if the current user has a required permission. I'd like to call on this service in my markup like this:
<input type="text" ng-model="name" ng-disabled="$permissions.check('edit-user')" />
So my questions are:
Thanks in advance.
Upvotes: 2
Views: 790
Reputation: 26880
Well, you can do it like that, but I prefer another approach. Instead of adding a $permissions
property to each $scope
(or to the $rootScope
), you can just use filters.
The permissions filter would look something like this:
app.filter('hasPermission', function(permissionsSvc) {
return function(input, invert) {
var hasPermission = permissionsSvc.check(input);
return (invert ? !hasPermission : hasPermission);
};
});
And the permissions service:
app.factory('permissionsSvc', function() {
return {
check: function(permission) {
// do the validation here and return true or false
}
};
});
On the markup:
<input type="text" ng-model="name" ng-disabled="'edit-user' | hasPermission:true" />
The true
after the filter is to invert the condition (second argument of the filter function), since we want to "disable if the user doesn't have the permission". That's just one way to do it, you could, for example, define another filter like hasNoPermission
that would do the opposite of the hasPermission
filter... it's a matter of tastes.
Upvotes: 4