Angularjs指令前评估pression - 可选属性 [英] Angularjs Directives Evaluating Expression - optional attribute
问题描述
我需要一个可选的禁用属性的自定义导航指令,我不知道,如果它甚至有可能。
在我的主控制器:
.controller('NavCtrl',['UserResource','RoleResource'],功能(UserResource,RoleResource){
变种用户= UserResource.getUser();
变种角色= RoleResource.getRoles();
UserService.init(用户,角色); // ????});
指令
.directive('的NavItem',函数(){
返回{
限制:'A',
范围: {
文字:'@',
HREF:'@',
ID: '@',
禁用:'和;' },
控制器:函数($范围,$元,$ ATTRS){
$ scope.disabled =''; //不知道我竟然需要一个控制器在这里
},
更换:真实,
链接:功能(范围,元素,ATTRS){
。范围$的eval(attrs.disable);
},
模板:'<李类={{禁用}}>< A HREF ={{HREF}}ID ={{ID}}> {{文本}}< / A> < /李>' }});
HTML - 我想要做这样的事情:
< DIV数据导航项文字=我的文本的href =/ mytemplate.htmlID =IDX禁用=UserService.hasRole(管理,计费)及和放大器; someOtherFn(XXX)|| ......>
您可以让你有什么工作,通过chaning你的$的eval调用
$范围母公司$的eval(attrs.disable)。
因为你需要评估包含在 attrs.disable
除权pression父范围,而不是指令的分离范围。然而,由于您使用的是'和;'语法,它会自动评估父作用域的前pression。所以只是做而不是以下内容:
如果(angular.isDefined(attrs.disable)){
scope.disable();
}
小提琴。
I have a custom navigation directive that needs an optional "disable" attribute, and I'm not sure if it's even possible.
In my main controller:
.controller('NavCtrl', ['UserResource','RoleResource'], function(UserResource,RoleResource){
var user = UserResource.getUser();
var roles = RoleResource.getRoles();
UserService.init(user, roles); //????
});
Directive
.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 - 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) || ...">
You could make what you have work by chaning your $eval call to
scope.$parent.$eval(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指令前评估pression - 可选属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!