Skip to content

Instantly share code, notes, and snippets.

@NizarOukhchi
Created August 6, 2015 09:23
Show Gist options
  • Save NizarOukhchi/8f1de2746e2ac1abc385 to your computer and use it in GitHub Desktop.
Save NizarOukhchi/8f1de2746e2ac1abc385 to your computer and use it in GitHub Desktop.
HasPermission directive
<div ng-app="app" ng-controller="appCtrl">
<h1>Has Permission directive</h1>
<div has-permission="role">I'm hidden when theses role requirements are not satifisfied
<p>hello {{role}}, you can see the video</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/uD6Okha_Yj0" frameborder="0" allowfullscreen></iframe>
</div>
<input type="text" ng-model="role">
</div>
angular.module('app', ['ngAnimate'])
.controller('appCtrl', function($scope, User){
$scope.role = 'asas';
})
.factory('User', function(){
var user = {};
user.roles = ['admin', 'user'];
user.hasRole = function(role) {
return user.roles.indexOf(role) > -1;
};
user.push = function(role) {
user.roles.push(role)
console.log(user.roles)
};
return user;
})
.directive('hasPermission', function($animate, User) {
return {
multiElement: true,
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
var block, childScope, previousElements,
getBlockNodes = function (nodes) {
var node = nodes[0];
var endNode = nodes[nodes.length - 1];
var blockNodes = [node];
do {
node = node.nextSibling;
if (!node) break;
blockNodes.push(node);
} while (node !== endNode);
return angular.element(blockNodes);
}
$scope.$watch($attr.hasPermission, function hasPermissionWatchAction(value) {
if (User.hasRole(value)) {
if (!childScope) {
$transclude(function(clone, newScope) {
childScope = newScope;
clone[clone.length++] = document.createComment(' end hasPermission: ' + $attr.hasPermission + ' ');
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
} else {
if (previousElements) {
previousElements.remove();
previousElements = null;
}
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
previousElements = getBlockNodes(block.clone);
$animate.leave(previousElements).then(function() {
previousElements = null;
});
block = null;
}
}
});
}
};
});
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular-animate.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment