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 Commented May 2, 2017 at 10:23
  • Easy answer. Use ng-if.. Commented 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>
Sign up to request clarification or add additional context in comments.

Comments

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 Comments

OP has said he does not need another custom filter for this.
@JinsPeter OP not said he does not need another custom filter .. but he said if not necessary . read again please!
It is not necessary. Easily achieved using an ng-if
I think using of ng-if directive is costly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.