当前位置: 首页 > 面试题库 >

AngularJS-有条件地使用属性指令

唐啸
2023-03-14
问题内容

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

<!--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。我不想为所返回的每个值创建两个大的重复<li>元素。换句话说,我不是在寻找以下方法来解决此问题。ng- if``dragSupported()

<!--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>

还有其他方法可以避免代码重复吗?


问题答案:

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

的官方文件 ng-attr

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

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

演示版

JSFiddle

这包含以下值用法的示例:truefalseundefinednull10,和""。请注意,通常为假的值可能如何产生意外结果。



 类似资料:
  • 在html: 在cmsText.js中 在cmsText.html 我希望输入标签中的“必需”字仅在设置为true时显示,在设置为false时该字消失。有人能帮忙吗?

  • 我想有条件地显示和隐藏这个按钮组,这取决于从父组件传递的内容,看起来像这样: .... .... 然而,{this.props.showBulkActions'show':'hidden'并没有发生任何事情。我做错什么了吗?

  • 更准确地说,我甚至想要更详细的东西:目标应该是一个包含三个属性的类,其中产生的目标值必须被拆分为三个属性。例如,如果mysource.propa的值为“abc”,那么目标myTarget应该得到一个类似于“v01.123.456.ab”的值。该值依次分为preValue、middleValue和endvalue: preValue=“V01” middleValue=“123.456”

  • 问题内容: 我想有条件地显示和隐藏此按钮组,具体取决于从父组件传入的内容,如下所示: .... .... 但是,{this.props.showBulkActions吗?’show’:’hidden’}。我在这里做错什么吗? 问题答案: 大括号位于字符串内,因此被评估为字符串。他们需要在外面,所以应该可以工作: 注意“向右拉”后的空格。您不希望偶然提供类“ pull-rightshow”而不是“

  • 问题内容: 我正在为指令模板。如果范围内的属性设置为true,则应将其附加到元素。如果变量为false,则此数据属性不应呈现为元素的属性。 例如,如果scope变量为true,则模板应呈现: 如果为false,则模板应呈现: 模板将如何完成此任务? 例如,我知道可以用来有条件地包含一个类。如果我希望模板呈现此内容: 然后我的模板如下所示: 如果scope变量为,则模板将简单地呈现: 因此,模板中有

  • 问题内容: 我需要能够根据作用域上的布尔变量向元素添加例如“ contenteditable”。 使用示例: 如果设置为,将导致contenteditable = true被添加到元素。有一些简单的方法可以实现这种ng- class这样的属性行为吗?我正在考虑编写指令,如果没有,请共享。 编辑: 我可以看到我提议的attrs指令和ng-bind- attrs 之间似乎有些相似之处,但是在1.0.0