0

Issue : I have a value that is coming from backend and needs to be on the dropdown(It needs to be the default selected value). The dropdown has set of values including that value. But somehow even after specifying that value in the scoep, It is not showing up in the frontend. Here is the code.
HTML

 <select class="bs-select form-control" ng-model="car.yearOfPurchase " id="year" name="year"  required="">
        <option ng-repeat="year in years" value="year">{{year}}</option>
 </select>

JS

 $scope.years = [];

  for (var i = 2002; i <= parseInt(moment().format("YYYY")); i++) {
        $scope.years.push(i.toString());
    }
    /*Value comign from backend. Mocked in this case.*/
  $scope.car = {
  yearOfPurchase : "2006" 
  };   
  $scope.year = $scope.car.yearOfPurchase;

Also, I have created a plunker for the same.

5
  • Can you replace your mock by the way it was really done before please? Commented Apr 18, 2016 at 11:50
  • I did not understand by the phrase "replace your mock"?? Commented Apr 18, 2016 at 11:51
  • You could build your select with ngOptions. Then just set your ngModel with a value from your list and angular will do the rest. Also are how do you get the value from the backend. Commented Apr 18, 2016 at 11:52
  • you said : " Mocked in this case." Commented Apr 18, 2016 at 11:52
  • by the way : simple mistake : <option ng-repeat="year in years" value="{{year}}">{{year}}</option> Commented Apr 18, 2016 at 11:53

1 Answer 1

2
 <select class="bs-select form-control" ng-model="car.yearOfPurchase" 
    id="year" name="year"  required="" 
    ng-options="year for year in years">
 </select>

Be carefull you had a trailing space in your ng-model.

I switched to ng-options instead of option with ng-repeat.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that worked. Apart from trailing space issue... Why wasn't it working with options tag? Any idea. Just trying to gain up some knowledge here.
the value attribute was bad. Every options of your select has the value "year"(the string). You may try with ng-value="{{year}}". But the best solution is to stick with ng-options.
Thanks that helped. :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.