Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
922 views
in Technique[技术] by (71.8m points)

angularjs - Conditionally adding data-attribute in Angular directive template

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.

For example, if scope variable is true, the template should render:

<span data-toggle="dropdown"></span>

If false, the template should render:

<span></span>

What would the template look like to accomplish this?


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>

If scope variable isDropDown is false, then the template will simply render:

<span></span>

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>

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...