Mike Anderson
Mike Anderson

Reputation: 597

Dynamic Select List Default Selected Item - Angular JS

I have the code listed below which works fine, however when i attempt to add ng-model and related ng-change to the select, an empty option is added. I understanding why, it is because on init the selectedOption for ng-model is empty.

What I want to do is set a default value so when I can use ng-change to set options IsSelected value to true when user selects it. I'm just not sure how to go about this, I have no issues doing this when I'm working with a static generated select list, but for some reason I can't figure it out for this dynamic generated list.

Any input is appreciated!

    <div ng-repeat="optionType in productDetailModel.OptionTypes">
         <select name="{{optionType.OptionTypeName}}">
            <option ng-repeat="option in optionType.Options"
             value="{{option.OptionValue}}">{{option.OptionValue}}
            </option>
         </select>
     </div>

Here's plunkr I mocked to give a basic idea of what I have in mind: http://plnkr.co/edit/xBDfc0XzDwsF0mBiFZOv?p=preview

Upvotes: 1

Views: 12267

Answers (3)

Pravin Abhale
Pravin Abhale

Reputation: 415

There is one directive of select element is ng-init but it call once while first time rendering, but if you change the options dynamically then it will not call again. So for that you need to set the model field with value in scope just below of your new option population logic.

$scope.modelName = $scope.Options[0]; // if array
$scope.modelName = $scope.Options[key]; // if Json Object

Upvotes: 0

KhainTCore
KhainTCore

Reputation: 116

The initial option is blank because the model is initially undefined. As tymeJV said, initializing your scope inside of your .js will define a default value that will be shown as selected initially.

$scope.modelName = $scope.optionType.Options[0];

It might be helpful to use ng-options instead of ng-repeat. One reason why it might be beneficial is that ng-options does not create a child scope (unlike ng-repeat). This could help simplify linking to your model and avoid confusion.

<select name="{{optionType.OptionTypeName}}" ng-model="modelName" ng-options="option for option in optionType.Options"> 
</select>

This article covers the basics of ng-options as well as discusses why it would be used as opposed to ng-repeat.

Hope this helps.

Upvotes: 2

tymeJV
tymeJV

Reputation: 104775

Use ng-options when using a select!

<select name="{{optionType.OptionTypeName}}" ng-model="someModel" ng-options="option as option for option in optionType.Options>
</select>

And then set the ngModel to the default option you want selected:

$scope.someModel = $scope.optionType.Options[0]

Upvotes: 1

Related Questions