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

使用示例:

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

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

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


当前回答

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

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

其他回答

实际上我在几个月前写了一个补丁(在freenode的#angularjs中有人问过这个问题)。

它可能不会被合并,但它非常类似于ngClass: https://github.com/angular/angular.js/pull/4269

不管它是否被合并,现有的ng-attr-*东西可能适合你的需求(正如其他人提到的),尽管它可能比你建议的更具ngclass风格的功能要笨拙一些。

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

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

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

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

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

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