在 Angular 指令模板中有条件地添加数据属性 [英] Conditionally adding data-attribute in Angular directive template
问题描述
我正在处理指令的模板.如果范围中的属性设置为 true,则应将 data-toggle="dropdown"
附加到元素.如果变量为 false,则此数据属性不应呈现为元素的属性.
I'm working on the template for a directive. If a property in the scope is set to true, data-toggle="dropdown"
should be appended to the element. If the variable is false, this data attribute should not render as an attribute of the element.
例如,如果 scope 变量为 true,则模板应呈现:
For example, if scope variable is true, the template should render:
<span data-toggle="dropdown"></span>
如果为 false,则模板应呈现:
If false, the template should render:
<span></span>
实现此目的的模板是什么样的?
What would the template look like to accomplish this?
例如,我知道我可以使用 ng-class
有条件地包含一个类.如果我想让模板呈现这个:
For example, I know that I can use ng-class
to conditionally include a class. If I want the template to render this:
<span class="dropdown"></span>
然后我的模板看起来像这样:
Then my template would look like this:
"<span ng-class="{ 'dropdown': isDropDown }"></span>
如果范围变量 isDropDown
是 false
,那么模板将简单地呈现:
If scope variable isDropDown
is false
, then the template will simply render:
<span></span>
因此,模板中有一种方法可以有条件地添加 class="dropdown"
.是否有允许我有条件地添加 data-toggle="dropdown"
的模板语法?
So there's a way in a template to conditionally add a class="dropdown"
. Is there a syntax for templates that allows me to conditionally add data-toggle="dropdown"
?
我为模板尝试过的一件事是:
One of the things I've tried for the template is:
"<span data-toggle="{ 'dropdown': isDropDown }"></span>
我对上述模板的想法是,如果范围变量 isDropDown
为真,data-toggle
的值将设置为下拉".如果isDropDown
为false,则data-toggle
的值将只是一个空字符串""
.不过这似乎不起作用.
My thinking with the above template is that if the scope variable isDropDown
is true, the value of data-toggle
will be set to "dropdown". If isDropDown
is false, then the value of data-toggle
would simply be an empty string ""
. That doesn't seem to work though.
推荐答案
我认为一个好方法是使用 ng-attr-
后跟要计算的表达式.在你的情况下,它会是这样的:
I think a good way could be to use ng-attr-
followed by the expression you want to evaluate.
In your case it would be something like:
<span ng-attr-data-toggle="{{ isValueTrue ? 'toggle' : 'notToggle' }}"></span>
这是一个带有示例的 fiddle.
Here's a fiddle with an example.
这篇关于在 Angular 指令模板中有条件地添加数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!