Ternary Operator Use In AngularJS

Introduction

Ternary operator is an important part of most programming languages. AngularJS also supports the ternary operator in expressions.

  • The ternary operator is used with Angular directives, such as ng-class and ng-style.
  • Ternary operator was added to Angular 1.1.5 and used from version 1.1.5 and up. This is how we use it.

    condition ? value1 : value2

  • If the condition is true, then value1 is returned, otherwise the value2 is returned.

Sample Code - Listing 1

  1. <script src="angular.js"></script>  
  2. <script>  
  3.     var app = angular.module('App', []);  
  4.     app.controller('ternaryController'function($scope) {  
  5.         $scope.EmployeeList = ['Tripat Bala singh''Mritunjay''Sushil''Omprakash'  
  6.             'Ravi''Nishant''Arpan''Dinesh''Rishi'  
  7.         ];  
  8.         $scope.myObj = {  
  9.             "color""black",  
  10.             "background-color""#eee",  
  11.             "font-size""15px",  
  12.             "padding""2px"  
  13.         }  
  14.         $scope.myObj1 = {  
  15.             "color""white",  
  16.             "background-color""gray",  
  17.             "font-size""15px",  
  18.             "padding""2px"  
  19.         }  
  20.     });  
  21. </script>  
  22.   
  23. <body ng-app="App">  
  24.     <div ng-controller="ternaryController">  
  25.         <div style="width:50%;text-align:center" ng-repeat="employee in EmployeeList">  
  26.             <h3 ng-style="($index+1)%2==0?myObj:myObj1">{{employee}}</h3>  
  27.         </div>  
  28.     </div>  
  29. </body>  

 The output of the above code looks like Figure 1.



Figure 1

Some other examples are below.

Listing 2

  1. $scope.EmployeeDetails = [{"Name""Tripat Bala singh",""Email":"[email protected]" },     
  2. {"Name"null"Email""[email protected]"}]    
  3. <p ng-style="myObj"><span>Welcome</span>      
  4. {{(EmployeeDetails[0].Name!=null)?EmployeeDetails[0].Name:EmployeeDetails[0].Email}}</p>     
  5. <p ng-style="myObj1"><span>Welcome</span>      
  6. {{(EmployeeDetails[1].Name!=null)?EmployeeDetails[1].Name:EmployeeDetails[1].Email}}<p>    
The above expression will check Employee Name. If the employee name is not empty, then it prints the employee name; otherwise, it prints the employee email.

The output looks like Figure 2.

 
Figure 2

You can also use this ternary operator with attributes, like ng-if or ng-show. See the below example.

ng-show = " { { ( condition ) ? true : false } } "

  1. <span ng-show="{{(EmployeeDetails[0].Name!=null) ? true : false}}">  
  2.   "{{EmployeeDetails[0].Name}}"</span>  
  3.   <span ng-show="{{(EmployeeDetails[1].Name!=null) ? true : false}}""{{EmployeeDetails[1].Name}}"</span>  
If employee name is not null, then employee name will be shown, otherwise not. 
 
The output looks like Figure 3.


Figure 3

Summary

In this blog, I discussed how we can use ternary operator using AngularJS.