在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.
例如,如果范围变量为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
为true,则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>
这是一个 小提琴 ,并带有示例.
Here's a fiddle with an example.
这篇关于在Angular指令模板中有条件地添加数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!