angularjsangularjs-scopeangularjs-select

How to reset ng-model variables to Null in AngularJS?


In AngularJS, I have the following sample code:

<select style="margin-left:5px;width:60px" id="product" ng-model="output.product">
<select style="margin-left:5px;width:60px" id="status" ng-model="output.status">

Within my UI screen, I have a button where the user can reset select drop-down values for both product and status but I am unsure how to reset both my ng-model scope output values to null for output.product and output.status.

I have tried scope.output = ""; but this doesn't seem to work.

Again, I have using AngularJS (v1.1).


Solution

  • I am not going to write an answer for AngularJS V1.1 because that version is no longer supported. See AngularJS Version Support Status.

    For version 1.7, reset the select by setting the model to null:

      $scope.reset = function() {
          $scope.choice.product = null;
          $scope.choice.status = null;
      }; 
    

    The DEMO

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
      $scope.choice = {};
      $scope.productChoices = ['product A', 'product B', 'product C', 'product D', 'product E'];
      $scope.statusChoices = ['active', 'pending', 'completed', 'cancelled'];
    
      $scope.reset = function() {
          $scope.choice.product = null;
          $scope.choice.status = null;
      };   
    });
    <script src="//unpkg.com/angular/angular.js"></script>
    
    <div ng-app="myApp" ng-controller="myCtrl">
    
      Select a product:
      <select ng-model="choice.product" ng-options="prd for prd in productChoices">
          <option value="">Select a product</option>
      </select>
      <br/> Select a status:
      <select ng-model="choice.status" ng-options="prd for prd in statusChoices">
          <option value="">Select a status</option>
      </select>
    
      <hr/> selected product: {{choice.product}}
      <br/> selected status: {{choice.status}}
      <br/>
      <button type="button" ng-click="reset()">
        Reset
      </button>
    </div>