0

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'},];
    }
  }
}]);
1
  • you can also use ng-selected for auto select the options dynamically Commented Jan 29, 2016 at 17:10

1 Answer 1

2

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.

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

Comments

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.