简体   繁体   中英

Angular.js ternery statement on HTML tag

 <h4 class="changecolor">{{driver.name}}&nbsp;</h4>
<h4 class="changecolor" ng-show="!driver.name">{{driver.officeEmail}}&nbsp;</h4>

If the driver.name is not available then show the driver.officeEmail

Is there a way to implement this in one line, using ternary statement?

If you only want to use one binding, try:

<h4 class="changecolor">{{driver.name || driver.officeEmail}}</h4>

This is called short-circuit evaluation . If driver.name is undefined, then driver.officeEmail will be shown instead.

The answer by @quantumwannabe works and is a better solution for this particular use case, but the OP asked about ternary which is also possible since version 1.2.x.

 angular.module("app", []) .controller('appCtrl', ['$scope', function($scope) { $scope.driver = {email : "test"}; } ]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <div ng-controller="appCtrl"> <h4 class="changecolor">{{driver.name ? driver.name : driver.email}}</h4> </div> </div> 

<h4 class="changecolor">{{(driver.name) ? driver.name : driver.officeEmail}}&nbsp;</h4>

这对我有用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM