Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I was able to dynamically creating multiple drop-down lists base on the same set of data in angularJS. However, I am having an issue trying to dynamically set the default value of each of the drop-down lists. For example, in my first drop-down list, I would like the first subject ("Writing") to be selected by default. Then I would like the second drop-down list to have the second subject ("Reading") to be selected and the third drop-down list to have the third subject ("Math") to be selected and so forth. To recap, each of my drop-down list has the same options, but it should be assigned to different model dynamically. Can you please tell me how I can dynamically set the default value of each of the dynamically generated drop-down lists that has the same options?

Please see the code in http://plnkr.co/edit/dmQFLP?p=preview.

Thank you in advance for your help!

Here is my controller code: var module = angular.module("myapp",[]);

module.controller('myCtrl',['$scope','myService', function ($scope,myService) {

$scope.subjects = myService.getSubjects();    
$scope.subjectSelected=[]
}])

module.factory('myService', [function () {
  return {
    getSubjects: function() {      
          return [ 
              { name: 'Writing', value: 'Writing'}, 
              { name: 'Reading', value: 'Reading'}, 
              { name: 'Math', value: 'Math'},
              { name: 'Art', value: 'Art'},
              { name: 'Social Studies', value: 'SocialStudies'},];
    }
  }
}]);
share|improve this question

1 Answer 1

Try to add ng-init="subjectSelected[$index] = subjects[$index].value" in the select tag to initialize the value.

E.g.

<div ng-repeat ="subject in subjects">
    <select class="form-control input-lg" 
            ng-init="subjectSelected[$index] = subjects[$index].value" 
            ng-model="subjectSelected[$index]"
            required="required" 
            ng-options="subject.value as subject.name for subject in subjects">
    </select> 
</div>

Hope it helps.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.