在 AngularJS 中有条件地应用属性的最佳方法是什么? [英] What is the best way to conditionally apply attributes in AngularJS?
问题描述
我需要能够根据作用域上的布尔变量向元素添加例如contenteditable".
I need to be able to add for example "contenteditable" to elements, based on a boolean variable on scope.
示例使用:
<h1 attrs="{'contenteditable=\"true\"': editMode}">{{content.title}}</h1>
如果 $scope.editMode
设置为 true
,将导致 contenteditable=true 被添加到元素中.有没有一些简单的方法来实现这个类似 ng-class 的属性行为?如果没有,我正在考虑编写指令并共享.
Would result in contenteditable=true being added to the element if $scope.editMode
was set to true
.
Is there some easy way to implement this ng-class like attribute behavior? I'm considering writing a directive and sharing if not.
我可以看到我提议的 attrs 指令和 ng-bind 之间似乎有一些相似之处-attrs,但是在1.0.0.rc3中被移除了,为什么会这样?
I can see that there seems to be some similarities between my proposed attrs directive and ng-bind-attrs, but it was removed in 1.0.0.rc3, why so?
推荐答案
当无法使用 ng-class 时(例如在设置 SVG 样式时),我使用以下内容有条件地设置类属性:
I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
同样的方法应该适用于其他属性类型.
The same approach should work for other attribute types.
(我认为您需要使用最新的不稳定 Angular 才能使用 ng-attr-,我目前使用的是 1.1.4)
(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)
这篇关于在 AngularJS 中有条件地应用属性的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!