AngularJS - 有条件地使用属性指令 [英] AngularJS - Use attribute directive conditionally

查看:75
本文介绍了AngularJS - 有条件地使用属性指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用draggable指令来支持图像拖动。但是,根据用户的角色,我需要禁用某些用户组的图像拖动。我使用了以下代码。

I am using "draggable" directive to support image dragging. However, as per the role of the user, I need to disable image dragging for certain groups of users. I have used following code.

<!--draggable attribute is used as handle to make it draggable using jquery event-->           
<li  ng-repeat="template in templates" draggable id="{{template._id}}" type="template" class="template-box">            
<!-- Images and other fields are child of "li" tag which can be dragged.-->                    
</li> 

方法 dragSupported 在模板范围内并返回 true false 。我不想为返回的每个值使用 ng-if 创建两个大的重复< li> 元素通过 dragSupported()。换句话说,我不是在寻找以下方法来解决这个问题。

The method dragSupported is in the template scope and returns true or false. I don't want to create two big duplicate <li> elements by using ng-if for each value returned by dragSupported(). In other words, I am not looking for the following approach to solve this.

<!--draggable attribute is used as handle to make it draggable using jquery event-->           
<li ng-if="dragSupported() ==true"  ng-repeat="template in templates" draggable id="{{template._id}}" type="template" class="template-box">            
<!-- Images and other fields are child of "li" tag which can be dragged.-->                    
</li>
<!--remove "draggable" directive as user doesn't have permission to drag file -->
<li ng-if="dragSupported() !=true"  ng-repeat="template in templates"  id="{{template._id}}" type="template" class="template-box">            
<!-- Images and other fields are child of "li" tag which can be dragged.-->                    
</li>

有没有其他方法可以避免代码欺骗?

Is there any other approach to avoid code duplicity?

推荐答案

ng-attr-< attrName>



Angular包含对有条件声明HTML属性的支持,作为动态标题的 ng-attr-< attrName> 指令。

ng-attr 的官方文档

Official Docs for ng-attr

在您的情况下,代码可能如下所示:

In your case, the code might look like this:

<li
    id="{{template._id}}"
    class="template-box"
    type="template"
    ng-repeat="template in templates"
    ng-attr-draggable="dragSupported() === true"
></li>



演示



JSFiddle

这包含以下值的用法示例: true false undefined null 1 0 。请注意,通常假值可能会产生意外结果。

This contains examples of usage for the following values: true, false, undefined, null, 1, 0, and "". Note how typically-falsey values may yield unexpected results.

这篇关于AngularJS - 有条件地使用属性指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆