1

I have a search bar that lets users filter based on their entry using angular. Now I want to be able to display a message like "Nothing matches your search" when the search word entered by the user doesn't match anything in the array.

I tried monitoring a user's input using ng-change and then I loop through the array searching every parameter for the user's input but that doesn't work out. Here's a sample of my code.

html

<input ng-model="search" ng-change="check(search)">
<h4 ng-if="found === 0 ">Nothing matches your search</h4>
<div ng-controller="imCtrl" ng-repeat="imprest in imprests | filter:search">
    <h2>{{imprest.name}}</h2>
</div>

controller

var office = angular.module('Office');

office.controller('imCtrl',[$scope,function('$scope'){
     $scope.imprests = [
          {name:'John'},
          {name:'Peter'}
     ]

     $scope.check = function (word) {
        var found = 0
        $scope.searching = true
        for (var i = 0; i < $scope.vendorForms.length; i++) {
            if($scope.imprests[i].name.includes(word){
                found++
            } 
        }
        $scope.found = found
        $scope.searching = true
        $scope.done = true
    }
})

Is it possible to know the length of the filtered array so I can display a message?

HackAfro
  • 720
  • 1
  • 12
  • 28
  • You can check this answer - https://stackoverflow.com/questions/15316363/how-to-display-length-of-filtered-ng-repeat-data?rq=1 – bugs_cena May 31 '17 at 17:21

3 Answers3

2

You can use an alias:

ng-repeat="imprest in imprests | filter:search as filtered"

Then you can access:

{{filtered.length}}
rrd
  • 5,789
  • 3
  • 28
  • 36
1

You can write an filter function and use it to filter your array in angular code, and then check it's length.

$scope.myFilter(){
   // ... here your logic 
   // you need to compare with $scope.search
   // and then return the new array and check it's length
}

in markup you can use like

<div ng-controller="imCtrl" ng-repeat="imprest in myFilter()">
    <h2>{{imprest.name}}</h2>
</div>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

You should be able to use (imprests | filter:search).length == 0 to do this and then instead of your ng-change function you can simply add an ng-show to show the error, like so:

<input ng-model="search">
<h4 ng-if="found === 0 ">Nothing matches your search</h4>
<div ng-controller="imCtrl" ng-repeat="imprest in imprests | filter:search" ng-show="(imprests | filter:search).length !== 0">
    <h2>{{imprest.name}}</h2>
</div>
<div ng-show="(imprests | filter:search).length === 0">
    <h2>No results found</h2>
</div>
Callum
  • 845
  • 11
  • 22