我希望能做的是"包装"用于"权限的ng-hide的行为"指令......所以我可以做以下
<a href="/" permit="false">Hide me</a>
如果我决定简单地删除&#34;一切都很好。来自dom的元素;但是,如果我尝试添加ng-hide然后重新编译元素。不幸的是,这会导致无限循环
angular.module('my.permissions', []).
directive 'permit', ($compile) ->
priority: 1500
terminal: true
link: (scope, element, attrs) ->
element.attr 'ng-hide', 'true' # ultimately set based on the user's permissions
$compile(element)(scope)
OR
angular.module('my.permissions', []).directive('permit', function($compile) {
return {
priority: 1500,
terminal: true,
link: function(scope, element, attrs) {
element.attr('ng-hide', 'true'); // ultimately set based on the user's permissions
return $compile(element)(scope);
}
};
});
我在没有优先权或终端的情况下尝试过但无济于事。我已经尝试了许多其他排列(包括删除&#39; permit&#39;属性以防止它不断重新编译,但它似乎归结为:它似乎不是一个修改元素属性的方法,并通过指令重新编译内联。
我确定有一些我不知道的东西。
答案 0 :(得分:0)
此解决方案假设您希望观察permit
属性的更改(如果更改)并将元素隐藏为使用ng-hide
指令。一种方法是观察permit
属性更改,然后在需要隐藏或显示元素时提供相应的逻辑。为了隐藏和显示元素,您可以在 source code 中复制ng-hide
指令中的角度。
directive('permit', ['$animate', function($animate) {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attr) {
scope.$watch(attr.permit, function (value){
// do your logic here
var condition = true;
// this variable here should be manipulated in order to hide=true or show=false the element.
// You can use the value parameter as the value passed in the permit directive to determine
// if you want to hide the element or not.
$animate[condition ? 'addClass' : 'removeClass'](element, 'ng-hide');
// if you don't want to add any animation, you can simply remove the animation service
// and do this instead:
// element[condition? 'addClass': 'removeClass']('ng-hide');
});
}
};
}]);
答案 1 :(得分:0)
angular.module('my.permissions', []).directive('permit', function($compile) {
return {
priority: 1500,
terminal: true,
link: function(scope, element, attrs) {
scope.$watch(function(){
var method = scope.$eval(attrs.permit) ? 'show' : 'hide';
element[method]();
});
}
};
});
答案 2 :(得分:0)
我正在使用此指令。这类似于ng-if但它会检查权限。
appModule.directive("ifPermission", ['$animate', function ($animate) {
return {
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function ($scope, $element, $attr, ctrl, $transclude) {
var block, childScope;
var requiredPermission = eval($attr.ifPermission);
// i'm using global object you can use factory or provider
if (window.currentUserPermissions.indexOf(requiredPermission) != -1) {
childScope = $scope.$new();
$transclude(childScope, function (clone) {
clone[clone.length++] = document.createComment(' end ifPermission: ' + $attr.ngIf + ' ');
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when it's template arrives.
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
}
};
}]);
用法:
<div if-permission="requiredPermission">Authorized content</div>