【发布时间】:2015-10-17 03:11:37
【问题描述】:
我正在尝试构建一个自定义指令,以在页面上显示项目或根据授权数据完全删除它们,我显然遗漏了一些东西,因为它不起作用,我很难弄清楚找出原因。
我一直在关注这里的指南: http://adamalbrecht.com/2014/09/22/authorization-with-angular-and-ui-router/
其中说要复制 NgIf 源代码,并对其进行修改(如下所示)。
我真的很困惑,因为它不仅没有按预期工作,而且即使我在指令中的函数调用中设置断点,它也永远不会到达这些断点。
我不确定我做错了什么。为了使用自定义指令,我需要执行的步骤中是否还有其他未记录的内容,或者我是否以某种方式错过了一个步骤?常规 ng-if 在同一页面上的工作就好了。
编辑:我应该注意 AuthorizeService.isAuthorizedForOne 返回一个承诺值,它是真或假。这在其他情况下也能正常工作。
'use strict';
/**
* @ngdoc directive
* @name ngIfPermission
* @restrict A
*
* @description
**/
var ngIfPermissionDirective = ['$animate', function($animate, AuthorizeService) {
return {
multiElement: true,
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
console.log("I am here");
var block, childScope, previousElements;
$attr.$observe("ngIfPermission", function(value){
console.log("I am there");
var permissions = JSON.parse(value.replace(/'/g, '"'));
AuthorizeService.isAuthorizedForOne(permissions).then(function(auth){
if (!childScope) {
$transclude(function(clone, newScope) {
childScope = newScope;
clone[clone.length++] = document.createComment(' end ngIfPermission: ' + $attr.ngIfPermission + ' ');
// 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 its template arrives.
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
},
function(err) {
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;
}
});
});
}
};
}];
我是如何引用它的:
<div ng-if-permission="['OOGY']">You can see this.</div>
<div ng-if-permission='["BOOGY"]'>or this</div>
【问题讨论】:
-
这是一个匹配替换
JSON.parse(value.replace("'", '"'));,使用正则表达式JSON.parse(value.replace(/'/g, '"')); -
谢谢,这是一个很好的收获,以后会省去我的麻烦。
标签: angularjs angularjs-directive angular-ng-if