1

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

2
  • 1
    All commenters, It doesnt work for angular V1.3 and above. OP's qn is valid
    – Jins Peter
    May 2, 2017 at 10:23
  • Easy answer. Use ng-if..
    – Jins Peter
    May 2, 2017 at 10:38

2 Answers 2

4

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>
0

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>

4
  • OP has said he does not need another custom filter for this.
    – Jins Peter
    May 2, 2017 at 10:36
  • @JinsPeter OP not said he does not need another custom filter .. but he said if not necessary . read again please!
    – Hadi J
    May 2, 2017 at 10:42
  • It is not necessary. Easily achieved using an ng-if
    – Jins Peter
    May 2, 2017 at 10:43
  • I think using of ng-if directive is costly.
    – Hadi J
    May 2, 2017 at 10:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.