ng-repeat filter null value not displaying

ぃ、小莉子 提交于 2020-01-03 13:57:50

问题


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's a plnkr with what I'm saying: http://plnkr.co/edit/cj3v1fuBu6sHVI7A4qlq?p=preview

The filter works when it's anything but a null but I'm trying to only the null ones to display. I could try changing all the null values to a default value string other than a null? Is there anywhere to get the filter to work with nulls?


回答1:


I think the only thing wrong was that you needed to return the entire object.

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

I've modified my code example below to take that 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:

function(actual, expected): The function will be given the object value and the predicate value to compare and should return true if the item should be included in filtered result.

plunkr




回答2:


You can filter null items without writing a custom filter.

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

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

Conversely, this will return all non-null items:

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

The double not operator converts any value to boolean: the first not operator ! converts a truthy value to a boolean false, the second one inverts the boolean back to true. In my tests the filter actually works just by using state:'' but I would use !! just to be on the safe side...




回答3:


| filter:{expression} is expecting a true or false evaluation, not an object. Therefore:

$scope.filter1 = function(p){
    return (p.state === 'on');
};

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



回答4:


You can do like this as well

<ul ng-repeat="p in foo" >
  <li ng-if = "p.states">{{p.name}}</li>
</ul>



回答5:


You can test for Null in the expression like this:

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


来源:https://stackoverflow.com/questions/25879507/ng-repeat-filter-null-value-not-displaying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!