我需要能够添加例如“contentteditable”元素,基于范围上的布尔变量。

使用示例:

<h1 attrs="{'contenteditable=\"true\"': editMode}">{{content.title}}</h1>

将导致contentteditable =true被添加到元素中,如果$scope。editMode被设置为true。 是否有一些简单的方法来实现这种ng-class属性行为?我正在考虑写一个指令,如果没有的话就分享。

编辑: 我可以看到,我提议的attrs指令和ng-bind-attrs指令之间似乎有一些相似之处,但它在1.0.0中被删除了。为什么是Rc3 ?


当前回答

为了让一个属性根据布尔检查显示特定的值,或者如果布尔检查失败则完全忽略,我使用了以下方法:

ng-attr-example = "{{参数。Type == 'test' ?'itWasTest': undefined}}"

使用示例:

< div ng-attr-class = "{{参数。Type == 'test' ?'itWasTest': undefined}}">

是否根据params.type的值输出<div class="itWasTest">或<div>

其他回答

能够让这个工作:

ng-attr-aria-current="{{::item.isSelected==true ? 'page' : undefined}}"

这里的好处是if项。isSelected为false,则该属性不会被渲染。

<h1 ng- atr -contenteditable="{{isTrue || undefined}}">{{content.title}}</h1> . > . {{content.title}

当isTrue=true时产生: < h1 contenteditable = " true " > {{content.title}} < / h1 >

当isTrue=false时: <标题> {{content.title}} < / h1 >

你也可以这样表达:

<h1 ng-attr-contenteditable="{{ editMode ? true : false }}"></h1>

对于输入字段验证,您可以执行以下操作:

<input ng-model="discount" type="number" ng-attr-max="{{discountType == '%' ? 100 : undefined}}">

只有当折扣类型定义为%时,才会将属性max应用到100

在Angular的最新版本(1.1.5)中,他们加入了一个名为ngIf的条件指令。它与ngShow和ngHide的不同之处在于,元素不是隐藏的,而是完全不包含在DOM中。它们对于创建成本高但不使用的组件非常有用:

<h1 ng-if="editMode" contenteditable=true>{{content.title}}</h1>