Search code examples
angularjsangular-filters

Angular resetting search variable


Okay so i have the following object:

    $scope.search = {};

this allows me to search through the following elements:

<div class="col-md-12" ng-repeat="question in questions | filter:search:strict">

Now one of the things i can do is to set a variable called category_id which then filters the category_id of each item:

    $scope.search.category_id = selected.id;

However there is a problem. once i try to reset it AKA call $scope.search.category_id = null

All result disapear.

So it seem it is searching for categories where id = null which is false in every case.

So my question is how do i reset it then?


Solution

  • You should delete the property from the object rather than setting it to null. That will remove it from being listed in the search criteria.

    delete $scope.search.category_id
    

    You can see how this is different from setting it to null below

    var a = { hello: 5 }
    console.log(a, Object.keys(a)) // Object {hello: 5} ['hello']
    
    a.hello = null
    console.log(a, Object.keys(a)) // Object {hello: null} ['hello']
    
    delete a.hello
    console.log(a, Object.keys(a)) // Object {} []