Search code examples
angularjsng-style

Angular ng-style with more than 2 conditional outputs


My text stye is dependent on 3 conditions:

condition1: color should be green

condition2: color should be blue

condition3: color should be red

Thus, there are 3 outputs for the same style (color).

I could come up with the following expression:

<p ng-style="condition1  ? { color:'green' } : { color: 'blue' }"> 

Is there a way to change the above code such that it can accommodate all the 3 conditions and outputs ?

EDIT: There are workarounds to achieve this using controller; but I was wondering whether this can be done in the html itself


Solution

  • Only apply color if any of the condition is true and use ?: operator to check for other conditions in false value. Do not apply style if none of the conditions are true.

    var app = angular.module("MyApp", []).controller("MyCtrl", function ($scope) {
        $scope.cond1 = false;
        $scope.cond2 = false;
        $scope.cond3 = true;
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <body ng-app="MyApp">
      <div ng-controller="MyCtrl">
         <p ng-style="cond1  ? { color:'green' } : cond2 ? {color: 'blue'} : cond3 ? {color: 'red'} : {color: ''}">Hello World!</p>
      </div>
    
    </body>