{{website.url}} Each web...">

How to filter an empty array by property?

I have it on ng-repeat

<tr ng-repeat="website in websites"> <td>{{website.url}}</td> </tr> 

Each website object from the websites array is as follows:

 { url: "example.com", groups: [] } 

Question: How to apply a filter to the above loop so that it displays only those elements where the groups property is an empty array?

Things I tried:

 data-ng-repeat="website in websites | filter: {groups: []}" data-ng-repeat="website in websites | filter: !groups.length" data-ng-repeat="website in websites | filter: groups.length === 0" 

(no errors in the console, but filters out everything)

 data-ng-repeat="website in websites | filter: {groups: ''}" 

(does the opposite of what I want and shows only those elements where groups not an empty array)

 data-ng-repeat="website in websites | filter: {groups: null}" 

(if instead of [] I use null to indicate the values ​​there, it works, but it seems really messy ... because I need to constantly look for the groups property, which becomes empty, and set it to null manually)

+6
source share
2 answers

I added a filter function to the controller:

JS:

 angular.module('myApp', []) .controller('myController', ['$scope', function($scope) { $scope.friends = [{ name: 'John', phone: '555-1276', a: [1, 2, 3] }, { name: 'Mary', phone: '800-BIG-MARY', a: [1, 2, 3] }, { name: 'Mike', phone: '555-4321', a: null }, { name: 'Adam', phone: '555-5678', a: [] }, { name: 'Julie', phone: '555-8765', a: [] }, { name: 'Juliette', phone: '555-5678', a: [] }]; $scope.filterFn = function(item) { // must have array, and array must be empty return item.a && item.a.length === 0; }; } ]); 

In your template:

 <table> <tr><th>Name</th><th>Phone</th><th>array len</th></tr> <tr ng-repeat="friend in friends | filter: filterFn"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.a.length}}</td> </tr> </table> 

Changed by Angular Filter doc plnkr

+4
source

You can use the comparator parameter as follows.

 <tr ng-repeat="website in websites | filter:{groups: []}:true"> <td>{{website.url}}</td> </tr> 

Angularjs white paper describes true .

true: abbreviation for the function (actual, expected) {return angular.equals (actual, expected)}. This is essentially a strict comparison of expected and actual.

jsfiddle here.

+2
source

Source: https://habr.com/ru/post/985036/


All Articles