javascript - ngAttr 与 Angular 的条件属性

标签 javascript html angularjs

我在 HTML 元素上有一个属性,我想根据一系列条件为其提供一个值。

例如,如果article.fields.category==='Example One',我想为我的元素提供属性am-icon,其值为示例一。但是,如果article.fields.category==='Another Example',则需要值another-example,依此类推整个列表。

我已经尝试过这个:

<i ng-attr-am-icon="{'example-one': article.fields.category==='Example One' || 'another-example': article.fields.category==='Another Example' || || 'third-example': article.fields.category==='Third Example'}"></i>

这不应用该属性,我很确定我写错了。但我似乎找不到有关 ngAttr 的文档或如何执行此操作的示例。

根据满足的条件,期望的结果将是以下之一:

<i am-icon="example-one"></i>
<i am-icon="another-example"></i>
<i am-icon="third-example"></i>

最佳答案

<i ng-attr-am-icon="{'example-one': article.fields.category==='Example One', 
                     'another-example': article.fields.category==='Another Example', 
                     'third-example': article.fields.category==='Third Example'}">
</i>
<小时/>

实际上上面的方法可能效果不太好,但@Deepika Kamboj 值得投票。为了纠正我的错误,也许......

<i ng-attr-am-icon="{{ getAttr(article.fields.category) }}"></i>

$scope.getAttr = function(val)  {
  return ($filter('lowercase')(val)).replace(' ', '-');
};

关于javascript - ngAttr 与 Angular 的条件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30301554/

相关文章:

javascript - 如何解决 Closure Compiler 中对象属性的重命名问题?

javascript - 如何在版本更改时重新加载资源(HTML/CSS/JS)

javascript - 在 Angular 中过滤单独的变量

php - 如何做一个 HTML 'upward' rowspan

ios - 如何在 ios 中的 Ionic 1/Ionic 2 应用程序中验证应用程序购买收据?

javascript - 如何从另一个选项卡中选择一个浏览器选项卡?

javascript - 在 Javascript 中设置延迟

javascript - 如何从 Highchart 获取元素属性

jquery - 滚动时将背景移出图片

javascript - 为什么 window.history.back() 会跳回两个状态?