Eric Mitjans
Eric Mitjans

Reputation: 2179

Reseting ng-option to default value from the Controller in AngularJS

I have the following select in my app:

<select ng-model="diagnose" ng-options="c as c.Name for c in diseases | orderBy:['Name']">
  <option value="">Diagnose*</option>
</select>

Once I send the data to the server, I reset the whole form, but the select goes to empty option instead of showing the empty value/hardcoded option.

I've tried with the following options:

$promisedb.then(function (data) {
  $scope.diagnose = [1];
});

And:

$promisedb.then(function (data) {
  $scope.diagnose = [0];
});

And:

$promisedb.then(function (data) {
  $scope.diagnose = '';
});

But so far no luck.

What am I missing?

Upvotes: 2

Views: 1334

Answers (1)

Omar Einea
Omar Einea

Reputation: 2524

I believe you could reset the select back to the default option using the delete command like so:

delete $scope.diagnose;

Demo:

angular.module('MyApp', []).controller('MyCtrl', function MyCtrl($scope) {
  $scope.diseases = [
    'Disease 1',
    'Disease 2',
    'Other diseases...'
  ];
  $scope.reset = function () {
    delete $scope.diagnose;
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
<body ng-app="MyApp">
  <div ng-controller="MyCtrl">
    <select ng-model="diagnose" ng-options="d for d in diseases">
      <option value="">Diagnose*</option>
    </select>
    <button ng-click="reset()">Reset</button>
  </div>
</body>

Upvotes: 3

Related Questions