How to apply conditional value of dynamic value in ng style?

I would like to apply background-colorwith ng-styleconditionally when the color value can be updated with$scope .

Here are my scope variables:

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

In fact, I do not use any conditions for applying the background color, this is done with:

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

The idea here is to apply this background color only whensomeone.id == mainId . I tried several solutions, but it seems this is not the correct syntax:

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

JSFiddle for testing

Does anyone have any idea how I can achieve this?

+4
source share
3 answers

This seems to be normal.

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

. - mainId , - : http://jsfiddle.net/fgc21e86/7/

+2

<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;
}]);
+3

You can do it like

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

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

+2
source

Source: https://habr.com/ru/post/1667855/


All Articles