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!

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Why is $scope.b falsy? Should it be a string?
@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 comparison
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.