如果我的服务中存在某些特定角色,我想创建一个像ngDisabled这样的属性指令来启用或禁用元素。
ObjectTypeConverter
在我的HTML上,我想使用这样的指令:
angular.module(...)
.service('RolesSerivce', function() {
this.hasRole = function(roleName) {
return this.roles.indexOf(roleName)>1;
};
this.setRoles = function(rolesArr) {
this.roles = rolesArr;
};
this.setRoles(['ROLE_CAN_CLICK'])
}).direcive('hasRole', function() {
??????????????????
// use RolesSerivce.hasRole inside implemetation
??????????????????
});
在上面的示例中,<button has-role="ROLE_CAN_CLICK" ng-disabled="extraValidation > 0">Click me</button>
指令必须覆盖has-role
,它必须是必需的。但ng-disable
ng-disable
为has-role
时必须运行true
。
我的问题,有人可以帮我指导实施吗?我怎么能这样做?
答案 0 :(得分:0)
试试这个:
angular.module(...)
.service('RolesService', function() {
this.hasRole = function(roleName) {
return this.roles.indexOf(roleName)>1;
};
this.setRoles = function(rolesArr) {
this.roles = rolesArr;
};
this.setRoles(['ROLE_CAN_CLICK'])
}).directive('hasRole', function(RolesService) {
return {
link: function (scope, element, attrs) {
$(element).removeAttr('ng-disabled');
if(RoleService.hasRole(attrs.hasRole)) {
$(element).removeAttr('disabled');
} else {
$(element).attr('disabled', 'disabled');
}
}
};
});
答案 1 :(得分:0)
创建真值表:
(extraValidation > 0)==true (extraValidation > 0)==false
ROLE_CAN_CLICK==true DISABLED ENABLED
ROLE_CAN_CLICK==false DISABLED DISABLED
创建一个与真值表匹配的表达式:
<button ng-disabled="(!ROLE_CAN_CLICK) || (extraValidation > 0)">
Click me
</button>