In my AngularJS (1.6) app, I have 3 variables and I'd like to assign a value to my template equal to any of these 3 variables. I need to use any of them, and it's likely that not all will be available.
This is why I need to have a logic OR. If any of those is available, I'd like my SPAN to get this value.
Is it possible to do it like this?
<span>{{ foo || bar || baz }}</span>
Thanks!
asked Mar 28, 2018 at 9:31
luthien
1,3054 gold badges17 silver badges27 bronze badges
2 Answers 2
It works but you have to be careful with what you show, here is an example:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a; // falsy -> undefined
$scope.b = 0; // falsy -> zero
$scope.c = "0"; // truthy -> 0 is displayed
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<code>Only $scope.c is displayed:</code>
<span>{{a || b || c}}</span>
</div>
answered Mar 28, 2018 at 9:41
Aleksey Solovey
4,1663 gold badges18 silver badges34 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
luthien
Why is $scope.b falsy? Should it be a string?
Aleksey Solovey
@luthien
0 is as falsy as false, so with || (short-circuit evaluation for logical operators) it would select the next truthy value, here is a full list for comparisonIt might be tidier if the logic checking the 3 variables is inside the controller.
<span ng-bind="getAnyValue()"></span>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
//the 3 variables
$scope.foo = null;
$scope.bar = 'bar has value';
$scope.baz = null;
//method checking who has value and return the first variable who got value
$scope.getAnyValue = function(){
var spanValue = 'all three are null'; //set value if all 3 variables are null
//just change the condition instead of != null
//to if your template is equal to any of these 3 variables
if($scope.foo != null){
spanValue = $scope.foo;
}
else if($scope.bar != null){
spanValue = $scope.bar;
}
else if($scope.baz != null){
spanValue = $scope.baz;
}
return spanValue;
}
});
</script>
Comments
default