简体   繁体   中英

ng-options default option that displays all options

I have a ng-options pick list that I want there to be a default option that displays all options; When you click an item in the list it should filter when you click on the default value it should show all values. I could have sworn in the past I was able to do this using an option html element with a value set to "", but this is not working, can someone help me work this out. Fiddle below.

http://jsfiddle.net/nzfks0rq/

<select ng-model="todoFilter" ng-options="todo.name as todo.name for todo in todos" class='form-control'>
   <option value="">Choose Vendor</option>
</select>
<ul class="unstyled">
  <li ng-repeat="todo in todos | filter:{name: todoFilter}">
     {{todo.name}}
  </li>
</ul>

thanks

The @mrust is right, but in your case you can just use simple search logic as that example provide

<div ng-init="friends = [{name:'John', phone:'555-1276'},
                         {name:'Mary', phone:'800-BIG-MARY'},
                         {name:'Mike', phone:'555-4321'},
                         {name:'Adam', phone:'555-5678'},
                         {name:'Julie', phone:'555-8765'},
                         {name:'Juliette', phone:'555-5678'}]"></div>

<label>Search: <input ng-model="searchText"></label>
<table id="searchTextResults">
  <tr><th>Name</th><th>Phone</th></tr>
  <tr ng-repeat="friend in friends | filter:searchText">
    <td>{{friend.name}}</td>
    <td>{{friend.phone}}</td>
  </tr>
</table>
<hr>

this code more important to understand how organize search by one or multiple fields using default filter

<label>Any: <input ng-model="search.$"></label> <br>
<label>Name only <input ng-model="search.name"></label><br>
<label>Phone only <input ng-model="search.phone"></label><br>
<label>Equality <input type="checkbox" ng-model="strict"></label><br>
<table id="searchObjResults">
  <tr><th>Name</th><th>Phone</th></tr>
  <tr ng-repeat="friendObj in friends | filter:search:strict">
    <td>{{friendObj.name}}</td>
    <td>{{friendObj.phone}}</td>
  </tr>
</table>

Best regards

Egor

You could create a custom filter to handle this. Here's an example from a previous post: https://stackoverflow.com/a/27118166/643779

Your problem is that your default options value is interpreted as null So in my opinion the easies way to solve your issue is just add watch to your filter and convert it to empty string when it's not defined.

$scope.$watch('todoFilter', function(val){
  $scope.todoFilter = $scope.todoFilter? $scope.todoFilter : "";
});

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM