You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ng-repeat中设置select默认值为空的问题

Hey there! Let's work through getting your select component to default to an empty value properly. The issue with your current approach is using value="?"—that sets the option's value to a literal question mark, not an empty value. Here are the reliable fixes depending on your setup:

原生HTML场景

The simplest correct way is to add an option with an empty string value (value="") and mark it as selected. This ensures the select starts with an empty state, not a placeholder value like "?".

<select name="your-select">
  <!-- Empty default option -->
  <option value="" selected>Choose an option...</option>
  <!-- Your actual options -->
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>

If you don’t add selected, most browsers will automatically select the first option anyway—but including it makes the behavior explicit and avoids edge cases.

前端框架场景(Vue/React)

If you’re using a framework, you’ll want to bind the select’s value to a reactive variable instead of relying on the selected attribute directly:

Vue Example

Bind your select to a data property initialized as an empty string:

<select v-model="selectedOption">
  <option value="">Choose an option...</option>
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>

<script>
export default {
  data() {
    return {
      selectedOption: '' // Initial empty value matches the empty option
    };
  }
};
</script>

React Example

Use useState to track the selected value, starting with an empty string:

import { useState } from 'react';

function CustomSelect() {
  const [selectedValue, setSelectedValue] = useState('');

  return (
    <select 
      value={selectedValue}
      onChange={(e) => setSelectedValue(e.target.value)}
    >
      <option value="">Choose an option...</option>
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option>
    </select>
  );
}

Quick Troubleshooting Tips

  • Double-check if any other option has the selected attribute—browsers will prioritize the last one with this attribute if multiple exist.
  • If your options are dynamically rendered (e.g., fetched from an API), make sure the empty option is added before the dynamic options.

内容的提问来源于stack exchange,提问作者Daniel Bezerra De Menezes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:12:01