Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 998
r0nn13 Avatar asked Mar 16 '26 05:03

r0nn13


1 Answers

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>
like image 101
MarcoS Avatar answered Mar 17 '26 17:03

MarcoS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!