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

查看:46
本文介绍了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 在模板范围内并返回 truefalse.我不想通过对 dragSupported() 返回的每个值使用 ng-if 来创建两个大的重复

  • 元素.换句话说,我不是在寻找以下方法来解决这个问题.

    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-

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

    ng-attr-<attrName>

    Support for conditionally declaring an HTML attribute is included with Angular as the dynamically-titled ng-attr-<attrName> directive.

    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

    这包含以下值的使用示例:truefalseundefinednull10"".请注意通常错误的值可能会产生意想不到的结果.

    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天全站免登陆