0

In Angular, I have an array like this:

$scope.items =["blue","red","pink","yellow"];

And another object (that I use for filtering)

$scope.filter={"color":{"blue":true, "pink":true},"shape":{"square":true}};

I would like to do a ng-if, so that

<ul>
    <li ng-repeat="n in items" ng-if="n in filter.color">
    </li>
</ul>

The ng-repeat would just display the elements in the $scope.items that exist in the $scope.filter

So, in other words, it would just display blue and pink

Thanks in advance!

2
  • 1
    can you post more of $scope.filter's content? you only have one color, how would it be if they were two? Commented Jan 4, 2018 at 18:17
  • Edited the post to show two colors on filter :) Commented Jan 4, 2018 at 18:19

2 Answers 2

2

You need a custom filter function:

<ul>
    <li ng-repeat="n in items | filter: yourFilter">
    </li>
</ul>

$scope.filter={"color":{"blue":true, "pink":true},"shape":{"square":true}};

$scope.yourFilter = function(item) {
  //will be true when color has a property with the color and it's true
  return $scope.filter.color[item];
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'll mark this as correct, even thought for Angular development is safer not to have ES6 expressions (for SEO reasons - it breaks the google crawler) so @sthames42 reply is safer as for today)
All the angular apps in my company are private, so I have this bad SEO habits. I will edit the answer
1

Since $scope.items is an array and $scope.filter is an object, you need a function to test the values:

angular.module('test', []).controller('testController', function($scope)
  {
  $scope.items =["blue","red","pink","yellow"];
  $scope.filter={"color":{"blue":true, "pink":true}};
  
  $scope.checkColor = function(value, index, array)
    {
    return $scope.filter.color[value];
    };
  });
  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="test">
<div ng-controller="testController">
<ul>
    <li ng-repeat="n in items | filter : checkColor">{{n}}</li>
</ul>
</div>
</body>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.