Ng-style with condition

I think it would be best to use ng-class for your problem. You then make a new class for the red background, eg:

<style>
    .red-background{
        background-color: red;
    }
</style>

And then use this class according to the condition:

<div data-ng-class="{'red-background':item.selected}">{{item.name}}</div>

(don't forget the single quotes around the class name, they are easily overlooked)


Try this code,

  <div data-ng-repeat="item in items">
       <div data-ng-style="item.selected && {'background-color':'red'}"> 
           {{item.name}}
       <div> 
    <div>

Please refer below

function simpleController($scope) {
    $scope.items = [

    {
        selected: false,
        name: 'first'
    }
,
       {
        selected: true,
        name: 'second'
    }
    ];
}
.red
{
background:red}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app>
    
    <body ng-controller="simpleController">
      <div data-ng-repeat="item in items">
           <div ng-class="{'red' :  item.selected}"> {{item.name}}
           <div> 
        <div> 
  
  </body>

</html>

Ironically I just looked this up, the correct thing is to obviously use classes as they have this designed within them.

However, you can do conditionals thanks to the JavaScript ability to return the last value with &&

<div ng-style="conditional && { 'background' : 'red' } || !conditional && { 'background' : 'green' }"> show me the background </div>

Tags:

Angularjs