uksz
uksz

Reputation: 18699

Select and NgModel issue with model

I have an issue with select tag and ngmodel. The value of the variable in the model is not represented in the options in the dropdown.

Here is the code:

<select ng-model="number">
  <option values="5">5</option>
  <option values="10">10</option>
  <option values="20">20</option>
  <option values="25">25</option>
</select>

Where number is defined in controller as 20.

After the compilation, the following HTML is added:

<option value="? undefined:undefined ?"></option>

NOTE:

I also presented number in the HTML view, and it has no problem with showing the number in the expression {{number}} - it is then displayed correctly.

Here is a plnkr:

http://plnkr.co/edit/IXfwByE5ZrA4y7z0y6mh?p=preview

Upvotes: 0

Views: 479

Answers (4)

Naga Sandeep
Naga Sandeep

Reputation: 1431

If the viewValue of ngModel does not match any of the options, then the control will automatically add an "unknown" option, which it then removes when the mismatch is resolved.

documentation here

Normally, angular will make an option selected, if the model's value matches with the value of one of the options.

10 is of value 10 and data type string where as your $scope.number = 10 makes it's value 10 of number type.

So model's value is mismatched.

Try $scope.number = '10' in your controller and it will work.

Upvotes: 1

Hassan Tariq
Hassan Tariq

Reputation: 740

$scope.number = 5+""; 

Add this statement in your controller instead of $scope.number=5 because value for option is string

Upvotes: 0

Nijeesh
Nijeesh

Reputation: 847

You have $scope.number=5. You should have

$scope.number = '5'   // a string. Change 5 to '5'

Upvotes: 0

Sherlocked Nguyen
Sherlocked Nguyen

Reputation: 594

You can try this way

<select name="mydata" ng-model="number" 
    ng-options="value for value in [5,10,20,25]">
</select>

in Controller

$scope.number = 20;

Upvotes: 1

Related Questions