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

如何为AngularJS下拉列表设置默认值?

Fixing Default Selection for Your AngularJS Dropdown

Hey there! Let's get that default value working for your dropdown. The main issue with your current code is that you're trying to set the default via ng-selected in a way that doesn't align with AngularJS's data-binding logic. Let's break down the best solutions for you.

AngularJS has a dedicated directive for dropdowns called ng-options that’s more efficient and cleaner than using ng-repeat for options. Here’s how to set it up with a default value:

Step 1: Update the HTML

Replace your existing <select> element with this:

<select class="form-control" ng-model="abc.code" required ng-options="x for x in codeList">
</select>

Step 2: Initialize the Model in Your Controller

The key to setting a default is to initialize your ng-model value directly in the controller—this follows AngularJS’s "data-driven" core philosophy. For example, if you want the second item in codeList to be the default:

// Inside your AngularJS controller
$scope.codeList = ['Option 1', 'Option 2']; // Replace with your actual option list
$scope.abc = {
  code: $scope.codeList[1] // Sets default to the second element in the list
};

This works because AngularJS binds the ng-model value directly to the dropdown’s selected option. When you set abc.code upfront, the dropdown will automatically select that value as soon as it loads.

If You Must Stick with ng-repeat

If you need to keep using ng-repeat for your options, you’ll need to fix the ng-selected logic and still initialize the model properly:

Updated HTML

<select class="form-control" ng-model="abc.code" required>
  <option ng-repeat="x in codeList" value="{{x}}" ng-selected="x === abc.code">
    {{x}}
  </option>
</select>

Controller Initialization

Same as the recommended approach—initialize abc.code in your controller to set the default:

$scope.codeList = ['Option 1', 'Option 2'];
$scope.abc = {
  code: $scope.codeList[1] // Default selection
};

The ng-selected attribute here checks if the current option’s value matches the ng-model value, ensuring the correct option is selected when the page loads.

Critical Tip

Always prioritize initializing the ng-model value in the controller over relying solely on ng-selected. This is especially important if your codeList loads asynchronously (like from an API)—initializing the model after the data loads will guarantee the default is set correctly once the options are available.

Add a safety check to avoid errors if codeList might be empty:

if ($scope.codeList && $scope.codeList.length > 0) {
  $scope.abc.code = $scope.codeList[1];
}

内容的提问来源于stack exchange,提问作者user11111

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:42:27