Ohad Sadan
Ohad Sadan

Reputation: 917

angular ng-options not selected value not render

I am creating select element and set the values with array
In my controller I set

$scope.numbers = _.range(20);
$scope.selectedNumber = 5;

and my html

    <select ng-model='selectedNumber' 
class='some-class' 
ng-options="item as item for item  in numbers" >
</select>

the css of the class is

.some-class{
   border:1px solid gray;
   border-radious:xxx;
   width:xxpx;
  heihgt:xxpx;
}

my problem is that the selected value does not rendered on page load only after clicking inside the select element. (also happens when I use ng-class instead of class).

if I remove the class then then it just renders fine.

(another quick question : why if I don't add ng-model the ng-options does not display any content

Upvotes: 1

Views: 1183

Answers (2)

Sidd Thota
Sidd Thota

Reputation: 2249

ng-options needs to be matching with ng-model in order to render the value.

For example if you ng-model is giving value of "Boston", you need to have that key/value pair or just the value in the object/array of your ng-options list. Its case sensitive as well.

Controller:

$scope.city = "Boston"; $scope.cityDetails = service.cityList;

Service:

$scope.cityList = {"Boston", "San Jose", "Chicago", "New York"};

so while trying to loop down, you need to loop in this way.

<select ng-model="city" ng-options="cityData for cityData in cityDetails"></select>

Upvotes: 1

maurycy
maurycy

Reputation: 8465

I've prepared few examples for you that I hope will help you understand, I don't know what's your $scope.numbers type if it's an array of integers, strings, or objects but the model has to be the same type, and if you want model to be object then it has to be passed by reference. Although to answer your question ng-model is mandatory when ng-options are used, if you don't want model you can use this pattern

<select>
  <option ng-repeat="number in numbers">{{number}}</option>
</select>

And here are different input types for the select, please visit plunker to see it working

$scope.numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  $scope.selectedNumber = 5

  $scope.numbersTwo = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
  $scope.selectedNumberTwo = '6'

  $scope.numbersThree = [{
    num: 0
  }, {
    num: 1
  }, {
    num: 2
  }, {
    num: 3
  }, {
    num: 4
  }, {
    num: 5
  }, {
    num: 6
  }, {
    num: 7
  }, {
    num: 8
  }, {
    num: 9
  }, {
    num: 10
  }]

  $scope.selectedNumberThree = $scope.numbersThree[7]

  $scope.selectedNumberFour = 8

http://plnkr.co/edit/7mzuj8Fg46xVv6bwhiOt?p=preview

Upvotes: 2

Related Questions