Ng-repeat null is not displayed

Why won't angular display values ​​that are null when I apply:

ng-repeat="p in foo | filter: filter2" 

where filter2 is

  $scope.filter2 = function(p){ if (p.state === null){ return p.state; } else{ return; } }; 

here is plnkr with what i am saying: http://plnkr.co/edit/cj3v1fuBu6sHVI7A4qlq?p=preview

A filter works when it has nothing but null, but I'm trying to display only nulls. Could I try changing all the null values ​​to a non-zero default value string? Is there somewhere for a filter to work with zeros?

+5
source share
4 answers

I think the only thing that was wrong was that you had to return the whole object.

Based on Brad's comment below, I went and checked the documents, and he is right. The only reason my sample code works is because it returns a "true" value.

I modified my sample code below to take this into account.

Here's the filter:

 $scope.filter2 = function(p){ if (p.state === null){ return true; } else{ return; } }; 

Here is the relevant section in the docs:

(actual, expected): the function will be assigned an object value and a predicate value for comparison and should return true if the element should be included in the filtering result.

plunkr

+6
source

You can filter null elements without creating a custom filter.

Using the code in your plunk, this will return null elements:

 <ul ng-repeat="p in foo | filter:{state:'!'}" > <li>{{p.name}}</li> </ul> 

And vice versa, this will return all nonzero elements:

 <ul ng-repeat="p in foo | filter:{state:'!!'}" > <li>{{p.name}}</li> </ul> 

The double operator does not convert any value to boolean: the first operator ! converts the true value to logical false , the second inverts the logical value back to true . In my tests, the filter actually only works with state:'' , but I would use it !! just to be safe ...

+14
source

| filter:{expression} | filter:{expression} expects true or false , not an object. Therefore:

 $scope.filter1 = function(p){ return (p.state === 'on'); }; $scope.filter2 = function(p){ return (p.state === null); }; 
+5
source

You can check the Null value in the expression as follows:

 ng-repeat="p in foo | filter:{state:null}" 
0
source

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


All Articles