如何使用 AngularJS 动态创建 CSS class

How to Dynamically create a CSS class using AngularJS

我有一个 Angular JS 网站,我在其中使用来自 API 的数据,我想用它来动态创建 CSS class。此 CSS class 将格式化来自 API 的其他数据,显示在 Angular JS 页面中。

例如,有没有办法在处理API数据时在Controller中创建Angular JS $scope数据,然后在相应的.html视图上,使用此 $scope 数据动态创建 CSS class ... 顺便说一下, $scope 数据不能在 HTML 'STYLE' 标记内使用,因为括号字符('{' 和 '}') 被视为 'STYLE' 个字符,因此它不允许 '{{' 和 '}}' 扩展 $scope 变量的值。

编辑: 以上评论基于使用 Visual Studio 2013 IDE,其中 Angular 语法显示为错误VS IDE。使用此语法(如下所示,Valentyn)允许 CSS class 定义动态属性并且效果很好。

您可以在 <style> 中使用 {{}}:

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

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

您可以为此尝试使用 ng-style

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