我正在构建一个指令,我正在调用“requires-authorization”来包装一个 ng-if 指令。我想按如下方式使用它:
<requires-authorization role='SuperUser'>
<!— super secret user stuff goes here, within
the scope of this view's controller —>
</requires-authorization>
我已经达到了:
angular.module('myApp').directive('requiresAuthorization', function() {
return {
template: '<div ng-if=\'iAmInRole\' ng-transclude></div>',
restrict: 'E',
transclude: true,
scope: {
role: '@'
},
controller: function($scope, UserService) {
$scope.iAmInRole = (UsersService.myRoles.indexOf($scope.role) !== -1);
}
};
});
这行得通,但是指令中包含的内容失去了它的范围,特别是它所在 View 的 Controller 的范围。我忽略了什么?
jsfiddle 供引用:http://jsfiddle.net/HbAmG/8/ 请注意 auth 值如何不显示在指令内,但在指令外可用。
最佳答案
ng-if
和 ng-transclude
指令都在您的指令中执行嵌入。在这种情况下,内置的嵌入机制无法正常工作,您应该自己实现 ngIf
以使其按预期工作:
JavaScript
app.directive('requiresAuthorization', function () {
return {
template: '<div ng-transclude></div>',
restrict: 'E',
transclude: true,
scope: {
role: '@'
},
controller: function ($scope) {
$scope.iAmInRole = true;
},
link: function(scope, element, attr, ctrl, transcludeFn) {
transcludeFn(function(clone) { // <= override default transclude
element.empty();
if(scope.iAmInRole) { // <= implement ngIf by yourself
element.append(clone);
}
});
}
};
});
笨蛋:http://plnkr.co/edit/lNIPoJg786O0gVOoro4z?p=preview
如果 ng-show
是您可以使用的选项,而不是 ng-if
,它也可能是一个非常简单的解决方法。唯一的副作用是隐藏数据将显示在 DOM 中并使用 CSS .ng-hide {display: none !important;}
隐藏。
JSFiddle:http://jsfiddle.net/WfgXH/3/
这篇文章也可能对您有用,因为它描述了类似的问题:https://stackoverflow.com/a/22886515/1580941
关于javascript - Angular : Directive transcluded scope lost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23201078/