0

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!

luthien
  • 1,285
  • 3
  • 15
  • 26

2 Answers2

1

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>
Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34
  • Why is $scope.b falsy? Should it be a string? – luthien Mar 28 '18 at 13:02
  • 1
    @luthien `0` is as falsy as `false`, so with `||` ([short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation) for logical operators) it would select the next truthy value, here is a [**full list**](https://stackoverflow.com/a/7615236/8495123) for comparison – Aleksey Solovey Mar 28 '18 at 13:06
1

It 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>

https://jsfiddle.net/ohxczy2p/1/

babidi
  • 506
  • 5
  • 6