javascript - 在 Angular JS 中动态应用 CSS 样式属性

标签 javascript angularjs ng-style

这应该是一个简单的问题,但我似乎找不到解决方案。

我有以下标记:

<div style="width:20px; height:20px; margin-top:10px; border:solid 1px black; background-color:#ff0000;"></div>

我需要将背景颜色绑定(bind)到范围,所以我尝试了这个:

<div style="{width:20px; height:20px; margin-top:10px; border:solid 1px black; background-color:{{data.backgroundCol}};}"></div>

那没有用,所以我做了一些研究并找到了 ng-style,但是那没有用,所以我尝试去掉动态部分,然后将样式硬编码到ng-style,像这样...

<div ng-style="{width:20px; height:20px; margin-top:10px; border:solid 1px black; background-color:#ff0000;}"></div>

这根本行不通。我是否误解了 ng-style 的工作原理?有没有办法将 {{data.backgroundCol}} 放入普通样式属性并让它插入值?

最佳答案

ngStyle指令允许您在 HTML 元素上动态设置 CSS 样式。

Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys. Since some CSS style names are not valid keys for an object, they must be quoted.

ng-style="{color: myColor}"

您的代码将是:

<div ng-style="{'width':'20px', 'height':'20px', 'margin-top':'10px', 'border':'solid 1px black', 'background-color':'#ff0000'}"></div>

如果你想使用作用域变量:

<div ng-style="{'background-color': data.backgroundCol}"></div>

Here fiddle 上使用 ngStyle 的示例,在运行代码段的代码下方:

angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
  $scope.items = [{
      name: 'Misko',
      title: 'Angular creator'
    }, {
      name: 'Igor',
      title: 'Meetup master'
    }, {
      name: 'Vojta',
      title: 'All-around superhero'
    }

  ];
});
.pending-delete {
  background-color: pink
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller='MyCtrl' ng-style="{color: myColor}">

  <input type="text" ng-model="myColor" placeholder="enter a color name">

  <div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
    name: {{item.name}}, {{item.title}}
    <input type="checkbox" ng-model="item.checked" />
    <span ng-show="item.checked"/><span>(will be deleted)</span>
  </div>
  <p>
    <div ng-hide="myColor== 'red'">I will hide if the color is set to 'red'.</div>
</div>

关于javascript - 在 Angular JS 中动态应用 CSS 样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21364445/

相关文章:

javascript - 使用 jQuery 对 DOM 节点进行排序 - 当前代码交替反转

javascript - AngularJs:如何在不同域上设置相同的cookie

angularjs - 如何检查 AngularJS 中是否指定了指令的方法参数?

javascript - 如何将字符串转换为 float 并将其存储到 double 类型的数组中?

javascript - 如何根据回调的响应在 componentDidMount 中设置状态

Angular 2 - 使用 ngFor 单独更改列表项背景颜色

javascript - 使用 ng-style 有什么缺点?

css - 为什么我们在 AngularJS 中使用 ng-style 而不是 style 进行 css 格式化?

javascript - 带悬停的 CSS 动态导航 - 如何让它在 iOS Safari 中工作?

javascript - Angular 1.5。 |单击子组件从父组件调用函数?