JVG
JVG

Reputation: 21150

Angular JS - Resetting a dropdown with a function

I have a listener set up in Angular to trigger an event when a select box's option changes.

I also have a button, which I want to "reset" the selection box to blank (NOT option 1).

Here's some code:

HTML:

<select id="dropdown" ng-model="orderProp" >
  <option ng-repeat="cats in categories" value="{{cats}}">{{cats}}</option>
</select>
<button id="showHide" ng-click="showAll($event)" >Show all results</button>

Javascript:

$scope.showAll = function($event){
    $scope.orderProp ="0";
}

Listener function on the select box:

   $scope.$watch( 'orderProp', function ( val ) {
        $scope.filteredMarkersProperty = $filter('filter')($scope.markersProperty, val);
        $scope.zoomProperty = 11;
        calcFocus();
    });

This KINDA works, although only sometimes, and I have no idea why it works (or doesn't) as I think it's the wrong way of going about it. I tried resetting it with jQuery .prop('selectedIndex',0);, but while this resets the index it doesn't trigger the listening function at all so this won't work.

Any ideas?

Upvotes: 8

Views: 24914

Answers (1)

user2264760
user2264760

Reputation:

First - take a look at ngOptions in the select directive: http://docs.angularjs.org/api/ng.directive:select

<select ng-options="cats for cats in categories" ng-model="orderProps"></select>

<button ng-click="orderProps='0'">Show all results</button>

This will work as long as '0' is not one of the categories. The select-box will show a blank when the value of orderProps does not match any of the values in categories.

Your $watch function is not a listener on the select box, it watches orderProps and orderProps can get changed outside the select box. If you want a listener on the select box you could add a ng-change="myOnChangeFn()".

Added a working plunkr: http://plnkr.co/edit/fqWkJBYOXGaYsK9Fnedc?p=preview

Upvotes: 12

Related Questions