luthien
luthien

Reputation: 1305

Angularjs data binding and logic OR

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!

Upvotes: 0

Views: 198

Answers (2)

babidi
babidi

Reputation: 506

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/

Upvotes: 1

Aleksey Solovey
Aleksey Solovey

Reputation: 4191

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>

Upvotes: 1

Related Questions