【问题标题】:Having a default Item in dropdown using angularjs使用 angularjs 在下拉列表中有一个默认项
【发布时间】:2017-05-01 20:40:34
【问题描述】:

我有这个非常好用的 html。我的 topicId 显示从 0 到 7,0 是第一项。 但是,当页面加载时,我的下拉列表中没有任何内容显示为默认值,直到我单击下拉列表。

我希望第一项显示为默认值。请问我怎样才能做到这一点?

        <div class="selectTopic">
            <select id="cTopic" name="cTopic" ng-model="selectedValue">
                <option ng-repeat="x in cuc.getData" value="{{x.topicId}}"> {{x.topicDescription}}</option> 
            </select>
        </div>

【问题讨论】:

  • 尝试将模型(selectedValue)设置为选项的 ng-repeat 集合中的第一项。
  • 怎么样?有代码示例吗?

标签: angularjs


【解决方案1】:

您应该改用 ngOptions。然后通过控制器将模型初始化为默认值:

<select id="cTopic" name="cTopic" ng-model="selectedValue" 
    ng-options="item.topicId as item.topicDescription for item in cuc.getData">
</select>

在控制器中:

$scope.selectedValue = "topicId1";

查看示例:

var app = angular.module('TestApp', []);

app.controller("testCtrl", function ($scope) {
	
  $scope.selectedValue = "topicId1";
  $scope.items = [
    {
      topicId : "topicId1",
      topicDescription :"topicDescription1"
    },
    {
      topicId : "topicId2",
      topicDescription : "topicDescription2"
    },
    {
      topicId : "topicId3",
      topicDescription  : "topicDescription3"
    }
  ];
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="TestApp" ng-controller="testCtrl">
    <div class="selectTopic">
        <select id="cTopic" name="cTopic" ng-model="selectedValue" ng-options="item.topicId as item.topicDescription for item in items">
        </select>
    </div>
</div>

【讨论】:

    【解决方案2】:

    你需要使用 ng-selected: https://docs.angularjs.org/api/ng/directive/ngSelected

     <div class="selectTopic">
        <select id="cTopic" name="cTopic" ng-model="selectedValue">
            <option ng-repeat="x in cuc.getData" value="{{x.topicId}}" 
                ng-selected="selectedValue === x.topicId"> 
                {{x.topicDescription}}
            </option> 
        </select>
     </div>
    

    但是,如果您使用纯 html,AngularJS 有更有效的方法来创建下拉菜单,请参阅:https://docs.angularjs.org/api/ng/directive/ngOptions

    【讨论】:

      【解决方案3】:

      建议的答案也可以,但是我倾向于使用的替代方法是:

      <div class="selectTopic">
      <select id="cTopic" name="cTopic" ng-model="selectedValue" ng-options="x.topicId as x.topicDescription for x in cuc.getData">
          <option value="">Select One ...</option> 
      </select>
      

      Angular 必须从一些未初始化的选择开始,因此在 html 中提供一个空白选项可以安全地初始化选择,而无需代表您的用户做出假设。

      【讨论】:

      • 我正在开发一个使用不同语言的应用程序,因此我无法在代码中使用“Select One”。一切都来自数据库
      • 我不确定你的意思?将存储在模型中的值是一个空字符串(如果您不选择其他内容)。
      • 我试过了,没有运气。下拉列表中的所有其他项目不再显示,只是显示第一个项目。选择一个..
      • 哦,我错过了 ng-options 中的一些内容,让我编辑
      猜你喜欢
      • 1970-01-01
      • 2013-11-23
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      • 2016-04-19
      • 2016-04-10
      相关资源
      最近更新 更多