11

I would like to apply a background-color with ng-style conditionally when the color value can be updated from $scope.

Here are my variables in scope:

$scope.someone = { id: '1', name: 'John', color: '#42a1cd' };
$scope.mainId = 1;

Actually I don't use any condition to apply the background color, it is done with:

<div ng-style="{'background-color': someone.color}">
    {{someone.name}}
</div>

The idea here is to apply this background color only when someone.id == mainId. I tried several solutions, but it does not seems to be the correct synthax:

  • ng-style="{{someone.id == mainId}} ? ('background-color': {{someone.color}}) : null"
  • ng-style="{ ('background-color': someone.color) : someone.id == mainId }"

JSFiddle for testing

Does someone have an idea of how I can achieve this?

Mistalis
  • 17,793
  • 13
  • 73
  • 97
  • 2
    Possible duplicate of [Angular ng-style with a conditional expression](http://stackoverflow.com/questions/19375695/angular-ng-style-with-a-conditional-expression) – Shadow The GPT Wizard Jan 26 '17 at 09:50
  • @ShadowWizard I think it is not a duplicate, as in your link the value of the style is **hard-coded**, and not **coming from scope**. – Mistalis Jan 26 '17 at 10:18
  • So? [This answer](http://stackoverflow.com/a/32245636/447356) is 100% the same as the accepted answer here, just replace the static values in there with the scope values. – Shadow The GPT Wizard Jan 26 '17 at 10:33

3 Answers3

11

This seems to work fine.

ng-style="{'background-color': person.id === mainId ? person.color : ''}"

See updated fiddle with two people - the one with mainId has a background color, while the other doesn't: http://jsfiddle.net/fgc21e86/7/

Fissio
  • 3,748
  • 16
  • 31
4

You may try like this

<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-style="{'background-color': getColor(someone)}">
    {{someone.name}}
  </div>
</div>

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.someone = {
    id: 1,
    name: 'John',
    color: '#42a1cd'
  };
  $scope.getColor = function(someone) {

        if($scope.mainId === someone.id) {
        return someone.color;
      }
  }
  $scope.mainId = 1;
}]);
Ashish Bakwad
  • 791
  • 4
  • 15
4

You could do it like

ng-style="someone.id == mainId ? {'background-color':'{{someone.color}}'} : {'background-color':'red'}"

Here's an updated fiddle http://jsfiddle.net/fgc21e86/9/

strwoc
  • 511
  • 1
  • 9
  • 18