1

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

1 Answer 1

1

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>
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.