neptune
neptune

Reputation: 1261

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

Upvotes: 1

Views: 429

Answers (2)

Jins Peter
Jins Peter

Reputation: 2469

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>

Upvotes: 4

Hadi
Hadi

Reputation: 17299

Try this.

var app = angular.module('app', [])
.controller('appCtrl', ['$scope',
  function($scope) {
    $scope.randomArray = [
      {
        prop1: 'val1',
        prop2: {
          value: '3',
          unit: 'l'
        }
      },
      {
        prop1: 'val2'
      },
      {
        prop1: 'val3',
        prop2: {
          value: '10',
          unit: 'l'
        }
      }
    ];
  }]);
  app.filter('check', function() {
  return function(items, tagName) {
    var filtered = [];
    angular.forEach(items, function(el) {
      if(el['prop2'] != undefined) {
        filtered.push(el);
      }
    });
    return filtered;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>

<div ng-app="app">
<div ng-controller="appCtrl">
             
  <div ng-repeat="random in randomArray | check:'prop2'">
  {{random}}
  </div>
  
  </div>
</div>

Upvotes: 0

Related Questions