Search code examples
angularjsangularjs-ng-repeat

Using Or Condition in ng-repeat statement


How can I use a Or condition in ng-repeat. I currently have

<div ng-repeat="waterSample in viewRequest.data.REV_SAMPLE_CMQREQUEST_WATER_SAMPLE">

It can be viewRequest.data.REV_SAMPLE_CMQREQUEST sometimes. It should look for viewRequest.data.REV_SAMPLE_CMQREQUEST_WATER_SAMPLE or viewRequest.data.REV_SAMPLE_CMQREQUEST How can I solve this


Solution

  • To achieve expected result, use below ternary condition to check property use REV_SAMPLE_CMQREQUEST_WATER_SAMPLE in viewRequest.data and use REV_SAMPLE_CMQREQUEST_WATER_SAMPLE or REV_SAMPLE_CMQREQUEST based on condition

         <div ng-repeat="waterSample in viewRequest.data.hasOwnProperty('REV_SAMPLE_CMQREQUEST_WATER_SAMPLE')? viewRequest.data.REV_SAMPLE_CMQREQUEST_WATER_SAMPLE : viewRequest.data.REV_SAMPLE_CMQREQUEST">
    {{wareSample}}
          </div>
    

    working code sample

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
      $scope.viewRequest = {
        data: {
          REV_SAMPLE_CMQREQUEST_WATER_SAMPLE : [
            {id: 1, name: "test1"},
            {id: 2, name: "test2"}
          ],
          REV_SAMPLE_CMQREQUEST:[
            {id: 100, name: "ABC1"},
            {id: 200, name: "ABC2"}
          ]
        }
      }
      
      $scope.conditionalArr = $scope.viewRequest.data.hasOwnProperty('REV_SAMPLE_CMQREQUEST_WATER_SAMPLE')? $scope.viewRequest.data.REV_SAMPLE_CMQREQUEST_WATER_SAMPLE : $scope.viewRequest.data.REV_SAMPLE_CMQREQUEST
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <body>
    
    <div ng-app="myApp" ng-controller="myCtrl"> 
    
      <div ng-repeat="waterSample in viewRequest.data.hasOwnProperty('REV_SAMPLE_CMQREQUEST_WATER_SAMPLE')? viewRequest.data.REV_SAMPLE_CMQREQUEST_WATER_SAMPLE : viewRequest.data.REV_SAMPLE_CMQREQUEST">
        {{waterSample.id}} {{waterSample.name}}
      </div>
    
    </div>
    
    
    
    </body>

    codepen - https://codepen.io/nagasai/pen/GVZRem?editors=1010