问题
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:
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.
来源:https://stackoverflow.com/questions/31150903/dynamically-creating-multiple-dropdown-and-auto-setting-each-dropdown-in-angular