Zelter Ady
Zelter Ady

Reputation: 6348

angularjs select option with value

I would like to create in angular (1.0) an select list with a default option who has value. I don't understand why, but when I add a value to default option, it is not rendered proper. My code is this:

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

<head>
  <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
  <script data-require="jquery@*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
  <script data-require="bootstrap@*" data-semver="3.3.6" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script data-require="angular.js@1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="myController">
  <h1>States in India</h1>
  <select ng-options="state for state in states" ng-model="selectedState">
    <option value="">-- choose --</option>
  </select>

  <br/>
  <br/>
  <h1>States in India - not working proper (default option not displayed)</h1>
  <select ng-options="state for state in states" ng-model="selectedState">
    <option value="not_empty">-- choose --</option>
  </select>
</body>

</html>

Can someone help me to understand this behavior? Why when I add the value attribute to default options it is no longer added to select?

Later edit: The issue I'd like to clarify is not about model, but about option element with not empty value:

<option value="not_empty">-- choose --</option>

I don't understand why this option is not rendered! If I add

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

then it appears (is rendered) inside drop down element! Plunker here: http://plnkr.co/edit/YDGodWKRqMROXjgEGXd2?p=preview

Upvotes: 3

Views: 9102

Answers (1)

If you choose to use ng-options you cant't add the default option with html, you need to bind the ngModel to one of the options:

<select ng-options="state.name for state in states" ng-model="selected">
</select>

This is a working example

If you want a message saying "Select State" you should use ng-repeat on the option tag:

<select ng-model="$ctrl.otherSelect">
  <option value="{{someValue}}">Select State</option>
  <option ng-repeat="state in states" value="state">{{state}}</option> 
</select>

Update: Fixed binding on value attribute

Upvotes: 3

Related Questions