这应该是一个简单的问题,但我似乎找不到解决方案。
我有以下标记:
<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/