Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a dynamic value in ng-style conditionally?

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?

like image 387
Mistalis Avatar asked Jan 26 '17 09:01

Mistalis


1 Answers

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;
}]);
like image 178
Ashish Bakwad Avatar answered Sep 23 '22 18:09

Ashish Bakwad