0

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

2
  • hi when get value null call function Commented May 16, 2016 at 11:45
  • What function? Can you demo a code? Commented May 16, 2016 at 11:55

2 Answers 2

2

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> 
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome. can you accept the answer if you are satisfied :)
1

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 = '';

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.