问题描述
我有一个自定义导航指令,需要一个可选的禁用"属性,我不确定它是否可能.
I have a custom navigation directive that needs an optional "disable" attribute, and I'm not sure if it's even possible.
在我的主控制器中:
.controller('NavCtrl', ['UserResource','RoleResource'], function(UserResource,RoleResource){
var user = UserResource.getUser();
var roles = RoleResource.getRoles();
UserService.init(user, roles); //????
});
在我的指令中:
.directive('navItem', function(){
return{
restrict: 'A',
scope: {
text: '@',
href: '@',
id: '@',
disable: '&'
},
controller: function($scope, $element, $attrs){
$scope.disabled = ''; //Not sure I even need a controller here
},
replace: true,
link: function(scope, element, attrs){
scope.$eval(attrs.disable);
},
template: '<li class="{{disabled}}"><a href="{{href}}" id="{{id}}">{{text}}</a></li>'
}
});
在我的 HTML 中,我想做这样的事情:
In my HTML, I want to do something like this:
<div data-nav-item text="My Text" href="/mytemplate.html" id="idx"
disable="UserService.hasRole('ADMIN,BILLING') && someOtherFn(xxx) || ...">
推荐答案
你可以通过将你的 $eval 调用更改为
You could make what you have work by chaning your $eval call to
scope.$parent.$eval(attrs.disable);
因为您需要计算父作用域中 attrs.disable
中包含的表达式,而不是指令的隔离作用域.但是,由于您使用的是&"语法,它将自动评估父作用域中的表达式.所以只需执行以下操作:
because you need to evaluate the expression contained in attrs.disable
in the parent scope, not the directive's isolate scope. However, since you are using the '&' syntax, it will evaluate the expression in the parent scope automatically. So just do the following instead:
if(angular.isDefined(attrs.disable)) {
scope.disable();
}
小提琴.
这篇关于AngularJS 指令中的可选表达式属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!