javascript 如何在 Angular 的 ng-class 中使用内联样式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23459537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use inline style within ng-class in Angular?
提问by AlejandroVK
I'm in a situation where I want to apply an inline style to a DOM element based in a flag that I have defined in a controller. The reason behind this is that I cannot change the existing CSS used in the view, nor extend it.
我处于一种情况,我想根据我在控制器中定义的标志将内联样式应用于 DOM 元素。这背后的原因是我无法更改视图中使用的现有 CSS,也无法扩展它。
That said, here is my current view code:
也就是说,这是我当前的视图代码:
<label class="control-label" ng-class="{'margin-left:100px' : is_modal}">Hello</label>
is_modal is just a flag that I switch to true/false in the controller when needed.
is_modal 只是一个标志,我在需要时在控制器中切换到 true/false。
The above code is not working, I've also tried:
上面的代码不起作用,我也试过:
<label class="control-label" ng-class="{'style=margin-left:100px' : is_modal}">Hello</label>
But does not work either. Anybody knows if this is possible? To define inline-styles?
但也不起作用。有谁知道这是否可能?定义内联样式?
Another option would be ng-style, but I can't seem to bind my controller flag is_modal to the ng-style, since it does not allow to ask for conditions as ng-class does...
另一种选择是 ng-style,但我似乎无法将我的控制器标志 is_modal 绑定到 ng-style,因为它不允许像 ng-class 那样要求条件......
Thanks Alejandro
谢谢亚历杭德罗
回答by ryeballar
If you're looking for an inline solution then this particular solution might work for you:
如果您正在寻找内联解决方案,那么此特定解决方案可能适合您:
<label class="control-label" ng-style="is_modal && {'margin-left': '100px'}">Hello</label>
but if you want to have a more consistent and maintainable solution with a complex set of conditions to append with your styling then I suggest you create a scope function that you may place in your ng-class
or ng-style
directive.
但是如果你想要一个更加一致和可维护的解决方案,并带有一组复杂的条件来附加你的样式,那么我建议你创建一个范围函数,你可以把它放在你的ng-class
orng-style
指令中。
e.g.
例如
HTML
HTML
<label class="control-label" ng-style="getStyle(is_modal)">Hello</label>
JAVASCRIPT
爪哇脚本
$scope.getStyle = function(is_modal) {
if(is_modal) {
return {
'margin-left': '100px'
}
}
};
See this EXAMPLE
看到这个例子
回答by Artem Petrosian
You can use ng-style
directive:
您可以使用ng-style
指令:
<label class="control-label" ng-style="is_modal && {margin-left:'100px'}">Hello</label>
回答by Tom
See this jsBin
看到这个jsBin
Create a function to evaluate isModal
and return the correct styles, like:
创建一个函数来评估isModal
和返回正确的样式,例如:
$scope.isModel = true; // or whatever
$scope.labelStyle = function() {
if ($scope.isModel) {
return {
'margin-left': '100px'
}
}
}
And then your markup would look like:
然后你的标记看起来像:
<label ng-style="labelStyle()">Hello</label>