Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

use

<selectng-model="mySelection"name=""id=""ng-options="x.value as x.label for x in myOptions"><optionvalue=""></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>

Solution 2:

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

<!DOCTYPE html><htmlng-app="app"><head><linkrel="stylesheet"href="style.css"><scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script></head><bodyng-controller="myController"><h1>Hello World!</h1><selectng-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 = '';

Post a Comment for "Angularjs Ng-options Removed Default Blank Value After Selecting An Option"