How to Dynamically create a CSS class using AngularJS

情到浓时终转凉″ 提交于 2019-12-23 17:26:08

问题


I have an Angular JS web site where I am using data from an API that I want to use to dynamically create a CSS class. This CSS class will then format other data from the API being displayed in an Angular JS page.

For example, is there a way for Angular JS $scope data to be created in the Controller while processing the API data and then on the corresponding .html view, use this $scope data to dynamically create a CSS class ... By the way, $scope data cannot be used inside the HTML 'STYLE' tag, because the bracket characters ('{' and '}') are treated as 'STYLE' characters, so it does not allow '{{' and '}}' to expand the value of a $scope variable.

EDIT: The above comments were based on using the Visual Studio 2013 IDE where the Angular syntax is shown as an Error in the VS IDE. Using this syntax (as shown below by Valentyn) allows a CSS class to define dynamic attributes and works great.


回答1:


You can use {{ and }} inside of <style>:

<style>
      .p { background-color: {{name}}; }
</style>

Try: http://plnkr.co/edit/MMgRJP0fFCowE1rxcULM?p=preview




回答2:


You can try use ng-style for this:

<element ng-style="function_result() or expression"></element>


来源:https://stackoverflow.com/questions/33990055/how-to-dynamically-create-a-css-class-using-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!