Search code examples
javascriptangularjsangular-filters

How to make angular empty filters match undefined and null values?


I've found a problem while typing a filter and then remove it, the collection keeps being filtered and not showing the items with undefined or null values in the filtered term.

An example code:

<div ng-app="App" ng-controller="AppController as app">
<p>
Filters
</p>
    Name: <input ng-model="listFilters.name" type="text"/>
    <br/>
    Short Description: <input ng-model="listFilters.shortDescription" type="text"/>

    <ul>
        <li ng-repeat="person in app.persons | filter:{name: listFilters.name, shortDescription: listFilters.shortDescription}">
            <p>{{person.name}}</p>
        </li>
    </ul>
</div>

The angular code:

angular.module('App', []);
angular.module('App').controller('AppController', AppController);
function AppController() {
        var ctrl = this;

    ctrl.persons = [
        {
            name: 'Bill',
            shortDescription: null
        }, 
        {
            name: 'Sally',
            shortDescription: 'A girl'
        },
        {
            name: 'Jhon',
        },
    ];
}

A working fiddle: https://jsfiddle.net/89pkcww2/

Steps to see the problem I'm talking about:

  1. Filter by name, the list is filtered.
  2. Erase the filter, see how the list is again displayed (Bill, Sally, Jhon).
  3. Filter by description, the list is filtered.
  4. Erase the filter, only the second value of the collection is displayed (Sally) the ones with undefined or nulls aren't. It's filtering by "empty string".

I guess this is a default behavior in Angular filters but... is there a way to change it? Do I have to make my own filter?

I want to filter by both properties separately, the collection | filter: filter.var does not serve this purpose.

Nor this is the same as filtering to show only not null values, it's closer to the opposite...


Solution

    1. shortDescription: null , it doesnt mean '' , null != '' , so when you delete the text from the 'short description' it doesnt show 'Bill' item.
      1. on third item there is not shortDescription at all so the ng-model="listFilters.shortDescription" cant bind to the property.
      2. only 'Sally' item works ok because the ng-model can bind to the property.