Search code examples
javascriptangularjsangular-filters

Filtering out objects with empty property from ng-repeat array


I have this array in scope:

$scope.randomArray = [
      {
        prop1: 'val1',
        prop2: {
          value: '3',
          unit: 'l'
        }
      },
      {
        prop1: 'val2'
      },
      {
        prop1: 'val3',
        prop2: {
          value: '10',
          unit: 'l'
        }
      }
    ];

Trying to make an ng-repeat through this only with objects having prop2 property set. I would not create a separate filter or scope function for this if not necessary, so I've tried this solution described here and here:

<div ng-repeat="random in randomArray | filter : { prop2 : '!!'}">
  {{random}}
  </div>

but it not works.

Here is the mcve: https://codepen.io/neptune01/pen/eWRBKd


Solution

  • A solution I come up with is this.Use ng-if for random.prop2. This works for prop2 being not null/undefined. Which is your case. For any other filtering you can use other methods

    <div ng-app="app">
    <div ng-controller="appCtrl">
    
      <div ng-repeat="random in randomArray" ng-if="random.prop2">
      {{random}}
      </div>
    
      </div>
    </div>