Issue
I am dynamically generating a select using ngrepeat from a $scope object and need to assign the default select option based on another value within the same $scope object: Here is current code:
<select id="group" ng-model="data.group" convert-to-number>
<option ng-repeat="item in data.groups" value="{{item.id}}">
{{item.group}}
</option>
</select>
{{data.group}}
Object in controller:
$scope.data = {
group: 2,
groups: [{
id: 1,
name: 'Group One'
},{
id:2,
name: 'Group Two'
},{
id:3,
name: 'Group Three'
}]
}
convert-to-number is a directive that converts $scope values to numbers to match with the id of the select options and everything works if I create hard coded options.
Once I dynamically generate the options with ng-repeat, it shows the correct options from data.groups in the select, and shows the correct group id in {{data.group}}, however the select box is blank and I have to click to see the options and when I select one it then updates {{data.group}} to the selected value of the option.
As mentioned with hard coded options all code works and the correct option is selected by default based on the {{data.group}} value.
Why is data.group not selecting the option in these dynamic options when first initialised?
Thanks
Solution
The way AngularJS works is by using ng-selected
within the <option>
tag to confirm which option matches the model. The following example code would work:
<option ng-selected="data.group == item.id"> ... </option>
Answered By - dat3450
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.