Search code examples
htmlangularjsfilterangular-filters

Building custom angular filter that filters by name


I am following this tutorial:

http://www.toptal.com/angular-js/a-step-by-step-guide-to-your-first-angularjs-app

In my controller, I have this function:

$scope.searchFilter = function (driver) {
    var keyword = new RegExp($scope.nameFilter, 'i');
    return !$scope.nameFilter || keyword.test(driver.Driver.givenName) || keyword.test(driver.Driver.familyName);
};

In my html, I have this line:

<tr ng-repeat="driver in driversList | filter: searchFilter">

And in my search bar in the html, I have this line:

<input type="text" ng-model="nameFilter" placeholder="Search..."/>

What is this doing in the searchFilter function:

return !$scope.nameFilter

Is it to account for when I type in nothing in the search bar? IF so, how does it work?


Solution

  • when $scope.nameFiler == '' (or null, undefined)

    searchFilter will returns true

    so, when user doesn't type anything in search box the filter should return all items.