AngularJS ng-style with a conditional expression

553,779

Solution 1

As @Yoshi said, from angular 1.1.5 you can use-it without any change.

If you use angular < 1.1.5, you can use ng-class.

.largeWidth {
    width: 100%;
}

.smallWidth {
    width: 0%;
}

// [...]

ng-class="{largeWidth: myVar == 'ok', smallWidth: myVar != 'ok'}"

Solution 2

simple example:

<div ng-style="isTrue && {'background-color':'green'} || {'background-color': 'blue'}" style="width:200px;height:100px;border:1px solid gray;"></div>

{'background-color':'green'} RETURN true

OR the same result:

<div ng-style="isTrue && {'background-color':'green'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

other conditional possibility:

<div ng-style="count === 0 && {'background-color':'green'}  || count === 1 && {'background-color':'yellow'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

Solution 3

You can achieve it like that:

ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"

Solution 4

@jfredsilva obviously has the simplest answer for the question:

ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"

However, you might really want to consider my answer for something more complex.

Ternary-like example:

<p ng-style="{width: {true:'100%',false:'0%'}[myObject.value == 'ok']}"></p>

Something more complex:

<p ng-style="{
   color:       {blueish: 'blue', greenish: 'green'}[ color ], 
  'font-size':  {0: '12px', 1: '18px', 2: '26px'}[ zoom ]
}">Test</p>

If $scope.color == 'blueish', the color will be 'blue'.

If $scope.zoom == 2, the font-size will be 26px.

angular.module('app',[]);
function MyCtrl($scope) {
  $scope.color = 'blueish';
  $scope.zoom = 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl" ng-style="{
   color:       {blueish: 'blue', greenish: 'green'}[ color ], 
  'font-size':  {0: '12px', 1: '18px', 2: '26px'}[ zoom ]
}">
  color = {{color}}<br>
  zoom = {{zoom}}
</div>

Solution 5

if you want use with expression, the rigth way is :

<span class="ng-style: yourCondition && {color:'red'};">Sample Text</span>

but the best way is using ng-class

Share:
553,779

Related videos on Youtube

TigrouMeow
Author by

TigrouMeow

merge keep

Updated on August 19, 2020

Comments

  • TigrouMeow
    TigrouMeow almost 4 years

    I am handling my issue like this:

    ng-style="{ width: getTheValue() }"
    

    But to avoid having this function on the controller side, I would much prefer to do something like this:

    ng-style="{ width: myObject.value == 'ok' ? '100%' : '0%' }"
    

    How can I do this?

    • Yoshi
      Yoshi over 10 years
      what version of angular are you using? At least with 1.1.5 this is possible without any changes. demo
    • TigrouMeow
      TigrouMeow over 10 years
      I am using 1.0.8 :) Oh too bad, I should really try to upgrade then... thanks!
    • BornToCode
      BornToCode over 6 years
      Although that with 1.1.5 your code is working, if you use other style properties instead of width (e.g. font-size) your code won't work until you change it to: ng-style="{ 'font-size': myObject.value == 'ok' ? '20px' : '10px' }" (must surround the style property with quotes).
    • Usman Iqbal
      Usman Iqbal over 6 years
      I dont know this is helpful but for new comers you can use ng style with an object but like this ng-style="objectBit ? { 'border':'1px solid red'} : { 'border': 'none' }"
  • TigrouMeow
    TigrouMeow over 10 years
    Okay, thanks! I just wondered if there was a way to do it without using any classes, but everything directly using Angular on the template.
  • MGot90
    MGot90 over 8 years
    ng-style is much faster than ng-class. If you have a large DOM with lots of conditionals it will be noticeable. Nevertheless this is clean.
  • Thanigainathan
    Thanigainathan over 8 years
    How to use this for more than one class names ?
  • 0x777
    0x777 over 8 years
    And if I'm using angular >1.1.5 ?
  • Lee
    Lee over 7 years
    This doesn't exactly answer the question.
  • Adam Plocher
    Adam Plocher almost 7 years
    How might I accomplish this but with multiple independent styles/conditions? Thanks, great answer btw.
  • Serj Sagan
    Serj Sagan almost 7 years
    This caused Uncaught Error: Template parse errors: Can't bind to 'ng-style' since it isn't a known property of 'div' error for me
  • netalex
    netalex over 6 years
    interesting syntax {<value>:'<string>'}[<$scope.var>]}, where it come from?
  • Rajnish Rajput
    Rajnish Rajput over 6 years
    @Arthur your example is going to check isTrue and {'background-color':'green'} OR it is going to check only isTrue and will put background how it will work please explain anyone?
  • Arthur Tsidkilov
    Arthur Tsidkilov over 6 years
    @rajnish-rajput it is going to check isTrue and put background, {'background-color':'green'} by default return true as a style object
  • JWiley
    JWiley almost 6 years
    This question literally asks for an example with ng-style and the accepted answer with 100+ votes does not provide that.
  • Bernardo Dal Corno
    Bernardo Dal Corno almost 6 years
    Syntax Error: Token '%3A' is%20an%20unexpected%20token at column 9 of the expression [ng-style%3A%...
  • Jouke
    Jouke almost 6 years
    this is the wrong answer, the answer from @Arthur below is correct.
  • Jeppe
    Jeppe almost 4 years
    This should be the accepted answer. It actually uses ng-style and allows for conditionals for each style.
  • Tuukka Haapaniemi
    Tuukka Haapaniemi over 3 years
    This does indeed work, but the syntax is really weird. Any links to documentation of this or any input on why it works with &&- and ||-operators?
  • hmd
    hmd about 3 years
    @ArthurTsidkilov what if I want to restrict ng-style to run only once? I can't use ng-class and controller scope variable, I need to calculate all containers heights at runtime but once a property is set I want to restrict it to avoid continues execution.
  • Kit
    Kit almost 3 years
    It's just using bracket notation to access the object. color['blueish'] == 'blue'