angularjs - 如何以 Angular 动态设置div的背景颜色?

标签 angularjs

这个问题在这里已经有了答案:





Apply CSS style attribute dynamically in Angular JS

(6 个回答)


4年前关闭。




我对 Angular 很陌生。我正在从后端 api 获取要显示的背景颜色。我想将它设置为 div 的背景颜色:

我试过了:

<div style="background-color: {{vitalItem.value.color}}" >

但颜色没有设置。在控制台中,它显示:
WARNING: sanitizing unsafe style value background-color: #d9534f (see http://g.co/ng/security#xss)

任何帮助表示赞赏..

编辑:

这是我的 html
<div class="latest-reading-box">
     <div class="latest-reading-container value-contain-type" ng-style="{'background-color': vitalItem.value.color}">
         <p class="p-time">{{vitalItem.value != null ? vitalItem.value.date : ""}}</p>
         <h3 class="latest-value">{{vitalItem.value != null ? vitalItem.value.value : ""}}</h3>
         <p class="type-value">{{vitalItem.value != null && vitalItem.value.vitalEntryType != 0 ?
                                                  getVitalEntryTypeName(vitalItem.value.vitalEntryType): ""}}</p>
     </div>
</div>

在 chrome 的检查中,这是看到的:
<div _ngcontent-c1="" class="latest-reading-container value-contain-type" ng-style="{'background-color': vitalItem.value.color}">
    <p _ngcontent-c1="" class="p-time">08 Jul, 2017</p>
    <h3 _ngcontent-c1="" class="latest-value">67</h3>
    <p _ngcontent-c1="" class="type-value"></p>
</div>

除了vitalItem.value.color 之外的所有东西都显示了它们的值(value)。为什么 ng-style 不起作用?

最佳答案

您可以使用 ng-style 来实现这一点

<div ng-style="{'background-color':vitalItem.value.color}" >

关于angularjs - 如何以 Angular 动态设置div的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45030949/

相关文章:

javascript - Angular js 将本地数组与全局范围绑定(bind)

jquery - 在企业应用程序中使用 angularJS 而不是(jquery + jqTemplate+jqValidationEngine+jqGrid)

javascript - Angular JS : What is the need of the directive’s link function when we already had directive’s controller with scope?

angularjs - 如何在ag-grid的社区版中实现Master-Detail组件

angularjs - Moment.js 未捕获的语法错误

javascript - 多个返回键json

angularjs - 如何提高sidenav动画性能 Angular Material

javascript - AngularJS - 一个没有名字的应用程序

javascript - 如何从 angularjs 工厂内的 $http.get() 返回数据

javascript - Angularjs 处理嵌套的 promise