如何在角度中使用默认选项.js选择框

How to have a default option in Angular.js select box

本文关键字:选项 默认 js 选择      更新时间:2023-09-26

我已经搜索了谷歌,找不到任何关于这个的东西。

我有这个代码。

<select ng-model="somethingHere" 
        ng-options="option.value as option.name for option in options"
></select>

有一些这样的数据

options = [{
   name: 'Something Cool',
   value: 'something-cool-value'
}, {
   name: 'Something Else',
   value: 'something-else-value'
}];

输出是这样的。

<select ng-model="somethingHere"  
        ng-options="option.value as option.name for option in options" 
        class="ng-pristine ng-valid">
    <option value="?" selected="selected"></option>
    <option value="0">Something Cool</option>
    <option value="1">Something Else</option>
</select>

如何将数据中的第一个选项设置为默认值,以便获得这样的结果。

<select ng-model="somethingHere" ....>
    <option value="0" selected="selected">Something Cool</option>
    <option value="1">Something Else</option>
</select>

你可以像这样简单地使用 ng-init

<select ng-init="somethingHere = options[0]" 
        ng-model="somethingHere" 
        ng-options="option.name for option in options">
</select>

如果你想确保你的$scope.somethingHere值在视图初始化时不会被覆盖,你需要在你的ng-init中合并(somethingHere = somethingHere || options[0].value(这个值,如下所示:

<select ng-model="somethingHere" 
        ng-init="somethingHere = somethingHere || options[0].value"
        ng-options="option.value as option.name for option in options">
</select>

试试这个:

.HTML

<select 
    ng-model="selectedOption" 
    ng-options="option.name for option in options">
</select>

爪哇语

function Ctrl($scope) {
    $scope.options = [
        {
          name: 'Something Cool',
          value: 'something-cool-value'
        }, 
        {
          name: 'Something Else',
          value: 'something-else-value'
        }
    ];
    $scope.selectedOption = $scope.options[0];
}

在这里普朗克。

如果确实要设置将绑定到模型的值,请将ng-options属性更改为

ng-options="option.value as option.name for option in options"

和 Javascript 到

...
$scope.selectedOption = $scope.options[0].value;

考虑到上述情况,这里的另一个 Plunker。

Srivathsa Harish Venkataramana只提到了track by一个答案,这确实是一个解决方案!

以下是如何在选择ng-options中使用track by的示例以及Plunker(下面的链接(:

<select ng-model="selectedCity"
        ng-options="city as city.name for city in cities track by city.id">
  <option value="">-- Select City --</option>
</select>

如果selectedCity是在角度作用域上定义的,并且它具有与cities列表中任何city的任何id具有相同值id属性,则会在加载时自动选择它。

这是Plunker的: http://plnkr.co/edit/1EVs7R20pCffewrG0EmI?p=preview

有关更多详细信息,请参阅源文档:https://code.angularjs.org/1.3.15/docs/api/ng/directive/select

我认为

,在包含"跟踪依据"之后,您可以在 ng-options 中使用它来获得您想要的内容,如下所示

 <select ng-model="somethingHere" ng-options="option.name for option in options track by option.value" ></select>

这种方式更好,因为当您想用对象列表替换字符串列表时,只需将其更改为

 <select ng-model="somethingHere" ng-options="object.name for option in options track by object.id" ></select>

其中 东西这里 当然是一个带有属性名称和 id 的对象。请注意,"as"不是以这种方式表示ng-options的,因为它只会设置值,并且在使用trackby

<select ng-model="foo"> <option ng-selected="$first" ng-repeat="(id,value) in myOptions" value="{{id}}"> {{value}} </option> </select>

----------------------编辑----------------
虽然这有效,但我更喜欢 @mik-t 的答案,当您知道要选择什么值时,https://stackoverflow.com/a/29564802/454252,它使用 track-byng-options 而不使用 ng-initng-repeat .

仅当您必须在不知道选择什么值的情况下必须选择第一项时,才应使用此答案。 例如,我将其用于自动完成,这需要一直选择第一项。

我的解决方案是使用 html 对我的默认选项进行硬编码。这样:

在 HAML 中:

%select{'ng-model' => 'province', 'ng-options' => "province as province for province in summary.provinces", 'chosen' => "chosen-select", 'data-placeholder' => "BC & ON"}
  %option{:value => "", :selected => "selected"}
    BC &amp; ON

在 HTML 中:

<select ng-model="province" ng-options="province as province for province in summary.provinces" chosen="chosen-select" data-placeholder="BC & ON">
  <option value="" selected="selected">BC &amp; ON</option>
</select>

我希望我的默认选项从我的 api 返回所有值,这就是我有一个空白值的原因。也请原谅我的哈姆。我知道这不是OP问题的直接答案,但人们在谷歌上找到了这个。希望这对其他人有所帮助。

使用以下代码填充模型中的选定选项。

<select id="roomForListing" ng-model="selectedRoom.roomName" >
<option ng-repeat="room in roomList" title="{{room.roomName}}" ng-selected="{{room.roomName == selectedRoom.roomName}}" value="{{room.roomName}}">{{room.roomName}}</option>
</select>

根据您有多少个选项,您可以将值放在数组中并像这样自动填充您的选项

<select ng-model="somethingHere.values" ng-options="values for values in [5,4,3,2,1]">
   <option value="">Pick a Number</option>
</select>

就我而言,我需要插入一个初始值只是为了告诉用户选择一个选项,所以,我喜欢下面的代码:

<select ...
    <option value="" ng-selected="selected">Select one option</option>
</select>

当我尝试使用空字符串 (null( 的值 != 的选项时,该选项被角度替换,但是,当放置这样的选项(带有 null 值(时,使用此选项选择 apear。

对不起,我的英语不好,我希望我能在这方面有所帮助。

selectngOptions一起使用并设置默认值:

有关更多ngOptions使用示例,请参阅 ngOptions 文档。

angular.module('defaultValueSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.data = {
    availableOptions: [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ],
    selectedOption: {id: '2', name: 'Option B'} //This sets the default value of the select in the ui
    };
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<body ng-app="defaultValueSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="mySelect">Make a choice:</label>
    <select name="mySelect" id="mySelect"
      ng-options="option.name for option in data.availableOptions track by option.id"
      ng-model="data.selectedOption"></select>
  </form>
  <hr>
  <tt>option = {{data.selectedOption}}</tt><br/>
</div>

plnkr.co

有关具有角度数据绑定的 HTML SELECT元素的官方文档

通过ngModel解析/格式化将select绑定到非字符串值:

(function(angular) {
  'use strict';
angular.module('nonStringSelect', [])
  .run(function($rootScope) {
    $rootScope.model = { id: 2 };
  })
  .directive('convertToNumber', function() {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        ngModel.$parsers.push(function(val) {
          return parseInt(val, 10);
        });
        ngModel.$formatters.push(function(val) {
          return '' + val;
        });
      }
    };
  });
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular.min.js"></script>
<body ng-app="nonStringSelect">
  <select ng-model="model.id" convert-to-number>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>
{{ model }}
</body>

plnkr.co

其他例子:

angular.module('defaultValueSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.availableOptions = [
     { name: 'Apple', value: 'apple' }, 
     { name: 'Banana', value: 'banana' }, 
     { name: 'Kiwi', value: 'kiwi' }
   ];
   $scope.data = {selectedOption : $scope.availableOptions[1].value};
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<body ng-app="defaultValueSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <select ng-model="data.selectedOption" required ng-options="option.value as option.name for option in availableOptions"></select>
  </form>  
  </div>
</body>

斯菲德尔

这对

我有用。

<select ng-model="somethingHere" ng-init="somethingHere='Cool'">
    <option value="Cool">Something Cool</option>
    <option value="Else">Something Else</option>
</select>

针对本·莱什的回答,应该有这样一句话

ng-init="somethingHere = somethingHere || options[0]" 

而不是

ng-init="somethingHere = somethingHere || options[0].value" 

那是

<select ng-model="somethingHere"
        ng-init="somethingHere = somethingHere || options[0]"
        ng-options="option.name for option in options track by option.value">
</select>

就我而言,因为表单中的默认值因情况而异。我在选择标签中添加了一个自定义属性。

 <select setSeletected="{{data.value}}">
      <option value="value1"> value1....
      <option value="value2"> value2....
       ......

在指令中,我创建了一个脚本来检查该值,当 angular 填充它时,将该值的选项设置为 selected。

 .directive('setSelected', function(){
    restrict: 'A',
    link: (scope, element, attrs){
     function setSel=(){
     //test if the value is defined if not try again if so run the command
       if (typeof attrs.setSelected=='undefined'){             
         window.setTimeout( function(){setSel()},300) 
       }else{
         element.find('[value="'+attrs.setSelected+'"]').prop('selected',true);          
       }
     }
    }
  setSel()

}(

刚刚从 Coffescript 中翻译了这个,如果不是洞的事情,至少它的要点是正确的。

这不是最简单的方法,但是当值发生变化时完成它

只需按如下方式使用ng-selected="true"

<select ng-model="myModel">
        <option value="a" ng-selected="true">A</option>
        <option value="b">B</option>
</select>
这对

我有用

ng-selected="true" 

我会在控制器中设置模型。然后,选择将默认为该值。前任:.html:

<select ng-options="..." ng-model="selectedItem">

角度控制器(使用资源(:

myResource.items(function(items){
  $scope.items=items;
  if(items.length>0){
     $scope.selectedItem= items[0];
//if you want the first. Could be from config whatever
  }
});

如果您使用ng-options来渲染,则默认选择与ng-mod具有相同值option则下拉列表。考虑以下示例:

<select ng-options="list.key as list.name for list in lists track by list.id" ng-model="selectedItem">

因此,具有相同值的选项 list.keyselectedItem ,默认为选中。

我需要默认的"请选择"是不可选择的。 我还需要能够有条件地设置默认选择选项。

我通过以下简单的方式实现了这一点:JS代码: 翻转这 2 个以测试选定的默认值或无默认值,默认的"请选择"文本 $scope.默认选项 = 0; $scope.defaultOption = { 键:"3",值:"选项 3" };

$scope.options = [
   { key: '1', value: 'Option 1' },
   { key: '2', value: 'Option 2' },
   { key: '3', value: 'Option 3' },
   { key: '4', value: 'Option 4' }
];
getOptions();
function getOptions(){
    if ($scope.defaultOption != 0)
    { $scope.options.selectedOption = $scope.defaultOption; }
}

.HTML:

<select name="OptionSelect" id="OptionSelect" ng-model="options.selectedOption" ng-options="item.value for item in options track by item.key">
<option value="" disabled selected style="display: none;"> -- Please Select -- </option>
</select>
<h1>You selected: {{options.selectedOption.key}}</h1>         

我希望这对有类似要求的其他人有所帮助。

"请选择"是通过Joffrey Outtier在这里的回答完成的。

如果你有一些东西,而不仅仅是初始化日期部分,你可以通过在控制器中声明它来使用它ng-init(),并在HTML的顶部使用它。此函数将像控制器的构造函数一样工作,您可以在那里启动变量。

angular.module('myApp', [])
 .controller('myController', ['$scope', ($scope) => {
   $scope.allOptions = [
     { name: 'Apple', value: 'apple' }, 
     { name: 'Banana', value: 'banana' }
   ];
   $scope.myInit = () => {
      $scope.userSelected = 'apple'
      // Other initiations can goes here..
   }
}]);

<body ng-app="myApp">
  <div ng-controller="myController" ng-init="init()">
    <select ng-model="userSelected" ng-options="option.value as option.name for option in allOptions"></select>
   </div>
</body>
    <!--
    Using following solution you can set initial 
default value at controller as well as after change option selected value shown as default.
    -->
    <script type="text/javascript">
      function myCtrl($scope)
        {
          //...
            $scope.myModel=Initial Default Value; //set default value as required
          //..
        }
    </script>
    <select ng-model="myModel" 
                ng-init="myModel= myModel"
                ng-options="option.value as option.name for option in options">
        </select>

在你的角度控制器中试试这个...

$somethingHere = {名称:"很酷的东西"};

您可以设置一个值,但您使用的是复杂类型,角度将搜索要在视图中设置的键/值。

并且,如果不起作用,请尝试以下操作:ng-options="option.value 作为选项中选项的 option.name 按 option.name"<</p>

div class="answers"跟踪>

我认为最简单的方法是

 ng-selected="$first"