how to use inline style within ng-class in Angular?
Solution 1
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.
e.g.
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
Solution 2
You can use ng-style
directive:
<label class="control-label" ng-style="is_modal && {margin-left:'100px'}">Hello</label>
Solution 3
See this jsBin
Create a function to evaluate isModal
and return the correct styles, like:
$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>
AlejandroVK
I'm a normal guy with a passion for technology and solving real life problems. I've worked for a long time in the R&D industry, participating in several IoT European research projects until I decided to create my own start-up with my colleague. Then I quickly moved to Web and Mobile development, using technologies like Python, Django-Flask, Javascript (Angular-Ember-React), MongoDB, PostgreSQL, Chef, Vagrant, Docker, Ansible, etc. In one word, I'm flexible, can switch back and front to devops as needed, and I learn fast.
Updated on June 08, 2022Comments
-
AlejandroVK almost 2 years
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.
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.
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...
Thanks Alejandro
-
AlejandroVK about 10 yearsGreat answer! This is what I need indeed, thank you!
-
AlejandroVK about 10 yearsThis is a good answer Tom, thank you, but since ryeballar answer is more complete, he gets the correct answer, I'll upvote your one too for pointing in the right direction too, thanks!