Search code examples
angularjsangular-ngmodel

AngularJS Show List Items based on ng-model


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.


Solution

  • 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.