Dean Christian Armada
Dean Christian Armada

Reputation: 7384

AngularJS ng-options removed default blank value after selecting an option

I am using ng-options for my select tag to have choices for the users. Everything works perfectly but after selecting an option for the first time the default blank value is gone. What if I want to revert back to the defaul blank value again? How can that be done? How can I retain that blank value?

Here is an example of my code:

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  </head>

  <body ng-controller="myController">
    <h1>Hello World!</h1>
    <select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions">

    </select>
  </body>

</html>

<script>
  var app = angular.module('app', []);
  app.controller('myController', function($scope){
    $scope.myOptions = [{
      "value": null,
      "label": null,
    },{
      "value": "First",
      "label": "First",
    },{
      "value": "Second",
      "label": "Second",
    },{
      "value": "Third",
      "label": "Third",
    }]
  });
</script>

Here is the plunker: http://plnkr.co/edit/5f17YxRfWFI4g40t3NEf?p=preview

Upvotes: 0

Views: 743

Answers (2)

Mostafa Maklad
Mostafa Maklad

Reputation: 347

Just add blank option to your options and select the blank by default like:

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  </head>

  <body ng-controller="myController">
    <h1>Hello World!</h1>
    <select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions">

    </select>
  </body>

</html>

<script>
  var app = angular.module('app', []);
  app.controller('myController', function($scope){
    $scope.mySelection = '';
    $scope.myOptions = [{
      "value": "",
      "label": "",
    },{
      "value": "First",
      "label": "First",
    },{
      "value": "Second",
      "label": "Second",
    },{
      "value": "Third",
      "label": "Third",
    }]
  });
</script>

here we add the blank option

{
  "value": "",
  "label": "",
}

and select that empty option $scope.mySelection = '';

Upvotes: 1

CodingNinja
CodingNinja

Reputation: 801

use

<select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions">
    <option value=""></option>
  </select>

Don't pollute your 'myOptions' with dummy null object, as APIs will not return you the same. you need to handle it on presentation layer, as shown above. while saving, if use selects empty, it will be saved as null (if handled properly)

also you can have something like this

<option value="">---select---</option>

Upvotes: 2

Related Questions