AngularJS Show List Items based on ng-model

2.2k views Asked by At

I'm trying to create some functionality where the user would have an input box and all the data (li's) below are hidden. Then when a user types into the input box, those li's that match that text are show.

What would the best way to do this using angular? I've set up plunker below: http://plnkr.co/edit/T6JOBJE4LrAtshbmaoPk?p=preview

I was thinking of setting the li's to:

li {
 display: none;
}

and then was going to try an ng-if with the ng-model as the value. Something like this:

  <div class="input-group">
    <span class="input-group-addon" id="basic-addon1">Search</span>
    <input type="text" class="form-control" ng-model="search">
  </div>    
    <ul>
      <li ng-repeat="x in data | filter:search " ng-if="!search">{{x.name}}</li>
    </ul>

Can someone help point me in the right direction? Even if its just explaining the logic.

2

There are 2 answers

0
Ilya Dmitriev On BEST ANSWER

You can just set ng-show attribute to your <ul> tag, where you will watch on length of search variable and if it's greater that zero, your list with filtered results will be shown. So, you don't need any css.

<ul ng-show="search.length">
  <li ng-repeat="x in data | filter:search ">{{x.name}}</li>
</ul>

Demo on plunker.

0
rom99 On

Part of your problem is the filter matches on the empty search string. You could create a custom filter to handle this, something like this http://plnkr.co/edit/i4lsuVUmOLO3pbISu7FR?p=preview

$scope.filterName = function(datum) {
  console.log($scope.search, datum);
  return $scope.search !== '' && datum.name.indexOf($scope.search) !== -1;
};

Used in the template like:

<ul>
  <li ng-repeat="x in data | filter:filterName">{{x.name}}</li>
</ul>

Then you would have greater control over the filter if you want to tweak it in future.