简体   繁体   English

如何为AngularJS设置select的默认选项?

[英]How do I set the default option for select with AngularJS?

I have been working on trying to set the default pre-selected option for angularJS and for some reason I can't. 我一直在尝试为angularJS设置默认的预选选项,由于某种原因,我无法这么做。 Here is a link to the relevant Plunkr . 这是相关Plunkr链接

Here is the relevant code: 以下是相关代码:

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

I've tried ng-init and a bunch of different ways; 我已经尝试了ng-init和许多其他方式。 I can't figure how to make the top option the preselected one. 我不知道如何使顶部选项成为预选的选项。

The linked answer suggests using ng-init . 链接的答案建议使用ng-init I would go with assigning default option into selectedOption in controller or directive's link function: 我会在控制器或指令的link函数中将默认选项分配给selectedOption

$scope.selectedOption = options[0]

I don't see a need to use another directive for this simple task. 我认为不需要为该简单任务使用另一个指令。

If what you want is to set one of the options pre-defined in options , in your ng-init do something like this $scope.selectedOption = <value> where <value> is the value property of the object you want to be marked as selected by default. 如果要设置options中预定义的options ,请在ng-init执行类似this $scope.selectedOption = <value> ,其中<value>是要标记的对象的value属性默认情况下选中。 For example 1 if your first object in options would be, {value: 1, name: "Option Number 1} . See code below: 例如1 ,如果你的第一个对象options是, {value: 1, name: "Option Number 1}请参见下面的代码:

$scope.options = [{value:1, name: "Option 1"}, {value:2, name: "Options 2"}];

$scope.selectedOption = 1;

On the other hand, if you only want to show a predefined option indicating the user to select one option (and not one of the options in your options )... This is a very simple (but effective way to achieve that). 另一方面,如果您只想显示一个预定义的选项来指示用户选择一个选项(而不是选项中的options )...,这是一种非常简单(但有效的方法)。 See code below: 参见下面的代码:

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

just update model of the element ie selectedOption='yourDefaultValue' 只需更新元素的模型,即selectedOption='yourDefaultValue'

What is the version of angular are you using? 您使用的是什么版本的angular? if the latest one, then you can use below code:: 如果是最新的,则可以使用以下代码:

    <select 
      ng-model="selectedOption" [ng-value]='yourDefaultValue'`
      ng-options="option.value as option.name for option in options">
    </select>

Link to updated plunkr : http://plnkr.co/edit/SkS0NqyXpnMcddu80anf?p=preview 链接到更新的plunkr: http ://plnkr.co/edit/SkS0NqyXpnMcddu80anf?p=preview

Updating model code moved in the function and also select as and track by should be avoided as mentioned in the angular doc 角度文档中所述track by应避免更新在函数中移动的模型代码以及select astrack by

Be careful when using select as and track by in the same expression.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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