Ace Hyzer Ace Hyzer - 1 year ago 85
AngularJS Question

Unselecting ng-options dropdown in AngularJS

I've created a select dropdown using ng-options that is used to filter a list on the page.When the page loads, the dropdown is blank and no filtering has occurred.

on initial page load

When I select an option, filtering happens properly, but the blank option disappears, and thus I am forced to have a department-filtered version of the list unless I refresh the page and start over:

Before Selecting, the blank option still there

Blank option gone

Here is my code:

.html file:

<select ng-model="search.SubDepartmentID" ng-options="d.SubDepartmentID as d.DepartmentLabel for d in DepartmentList"></select>

<br />
<div class="span10">
<!--Body content-->

<li ng-repeat="(index,e) in filteredEmployees | filter:search | orderBy:orderProp | startFrom:(currentPage - 1)*pageSize | limitTo:pageSize"
class="thumbnail employee-listing">
<a href="#/Employee/{{e.EmployeeID}}" class="thumb">
<img style="height: 100px; width: auto;" ng-src="../Images/CurrentEmployees/{{e.ImageName}}"></a>
<p><a href="#/Employee/{{e.EmployeeID}}">{{e.FullName}}</a></p>

I want to be able to return it to the blank option so that I have a completely unfiltered list. Doing a value="" option or just completely empty doesn't work, because it's filtering based on value, and nothing matches the empty value.

Any Help or direction would be much appreciated!

Answer Source

Thanks everyone for the responses, I took a mix of a few of your responses, added in a watch and achieved what I wanted, here is what I ended up with:

<select ng-model="search.SubDepartmentID" ng-options="d.SubDepartmentID as d.DepartmentLabel for d in DepartmentList"><option value=""></option></select>

So I did add the empty value, but I modified the watch that I already had in my controller to set the $ to undefined if it comes back null:

$scope.$watchCollection('[search.$, search.Status, search.SubDepartmentID]', function (newSearch) {
    if ($ != undefined) {
        if ($ == null) {
            $ = undefined;

The $ is undefined upon page load, and resetting it to undefined on select of the empty value did the trick!

Thanks again for all your help!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download