简体   繁体   中英

Angular Select Adding undefined option

I have this tempScale object defined in my controller:

$scope.tempScale = {
    scaleType : [],
    deviations : [],
    intervals : 0
};

Which connects to my html:

<select id="scales" ng-model="tempScale.scaleType" class="form-control">
    <option value="Manually Calculated" ng-selected="true">Manually Calculated</option>
    <option value="Automatically Calculated">Automatically Calculated</option>
</select>

I added in the ng-selected=true so that manually calculated would be the first and selected option (basically a default option 1), however, when I run the page, my HTML looks like:

<select id="scales" ng-model="tempScale.scaleType" class="form-control ng-valid ng-dirty ng-touched">
    <option value="? undefined:undefined ?"></option>
    <option value="Manually Calculated" ng-selected="true" selected="selected">Manually Calculated</option>
    <option value="Automatically Calculated">Automatically Calculated</option>
</select>

Why are those ng classes appearing on load, and where is this undefined option value coming from? It's not a loop, so I'm baffled.

You do not need ng-selected . Set the model from the controller as $scope.tempScale.scaleType='Manually Calculated'; .

One cannot set a default selected item when using ng-model directive with select element. The select element is bind to model field, which data is undefined. What value select should display? Yes, undefined. You try to pass data via markup, it is not an Angular way. Just keep your data in JS model, not in HTML markup.[ Ref ]

Plunker demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM