在AngularJS中有条件地应用属性的最佳方法是什么? [英] What is the best way to conditionally apply attributes in AngularJS?

查看:54
本文介绍了在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样式时),我将使用以下条件有条件地设置class attr:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆