Search code examples
javascriptangularjsfilterangular-filters

Implementing search in AngularJS: default way


I've implemented the default search in my angularjs app, the code is as below:

<div>
<input type="text" ng-model="searchKeyword" placeholder="Search records...">
<div class="checkbox" ng-repeat="record in records | filter: searchKeyword">
<label class="ms-pl-xs">
  <input type="checkbox">{{record.value}}&nbsp;[{{record.count}}]
</label>
</div>

The issue I'm facing here, is, suppose someone happens to fire up some keyword that isn't there in the records that are being ng-repeated. I want a message to come up, stating "Nothing found" or whatsoever.

How do I implement that logic? I've gone through different articles and several questions over here, couldn't find anything in this regard. How do I see for whether the length of the terms searched is zero, so that I can ng-if that thing and display the message? Thanks!


Solution

  • If you are using Angular 1.3+, you can use an alias:

    <div>
      <input type="text" ng-model="searchKeyword" placeholder="Search records..." />
      <div class="checkbox" ng-repeat="record in records | filter: searchKeyword as found">
        <label class="ms-pl-xs">
          <input type="checkbox">{{record.value}}&nbsp;[{{record.count}}]
        </label>
      </div>
      <div ng-if="found === 0">
        Nothing found
      </div>
    </div>
    

    If instead you have to use an older Angular, you can assign the result of the filter to a new array, and then check it's length:

    <div>
      <input type="text" ng-model="searchKeyword" placeholder="Search records..." />
      <div class="checkbox" ng-repeat="record in filteredRecords = (records | filter: searchKeyword)">
        <label class="ms-pl-xs">
          <input type="checkbox">{{record.value}}&nbsp;[{{record.count}}]
        </label>
      </div>
      <div ng-if="filteredRecords.length === 0">
        Nothing found
      </div>
    </div>