简体   繁体   English

Angular JS Multiple Select Options添加了额外的? 选项

[英]Angular JS Multiple Select Options adding extra ? Option

I am populating my multiple select like this : 我正在这样填充我的多个选择:

<select ng-model="myAddress" ng-options="address.addressLines for address in search.result.addresses" >
</select>

And there is 2 items currently. 目前有2个项目。 But when I load the page it seems to add an extra blank row as such 但是当我加载页面时,似乎添加了一个额外的空白行,例如

<option value="?" selected="selected" label=""></option>

But then when I click on my actual 2 item rows the above error row disappears. 但是,当我单击我的实际2行时,以上错误行消失了。 Any idea what is causing this ? 你知道是什么原因造成的吗?

When the select is initially loaded into the view, the model (myAddress) is not set from the controller. 当选择最初加载到视图中时,未从控制器设置模型(myAddress)。 Angular needs a way to represent this, so it adds an empty option to the select box. Angular需要一种表示方法,因此它向选择框添加了一个空选项。 Once a selection is made, it is populated and gets rid of the empty option because it is not defined in the list that is bound to the select. 一旦做出选择,它就会被填充并摆脱空选项,因为未在绑定到该选择的列表中定义它。

If you don't want a blank option to appear, you need to set a valid $scope.myAddress in the controller to be used as the default. 如果不想出现空白选项,则需要在控制器中设置一个有效的$ scope.myAddress用作默认值。

Depending on what you want to accomplish, there are really three options. 根据您要完成的工作,实际上有三种选择。

  1. You keep it as it works now where an empty option is available before a selection is made. 您可以将其保留为现在可用,在进行选择之前可以使用空选项。
  2. Set an initial value in the controller so there will be no empty option available. 在控制器中设置一个初始值,这样就不会有空选项。
  3. Always have an empty option available, even if a value has been set to the select. 即使已将值设置为选择值,也始终有一个空选项可用。

Example here : 这里的例子:

HTML: HTML:

<div ng-app="myApp" ng-controller="MainController">
    Select with no value set in controller:<br />
    <select ng-model="select1" ng-options="item.name for item in items">
    </select> {{select1}}
    <br /><br />
        Select with value set in controller:<br />
    <select ng-model="select2" ng-options="item.name for item in items">
    </select> {{select2}}
    <br /><br />
        Select empty option always available (even after selection):<br />
    <select ng-model="select3" ng-options="item.name for item in items">
        <option value=""></option>
    </select> {{select3}}
</div>

Javascript: 使用Javascript:

angular.module("myApp", [])

.controller("MainController", function ($scope) {
    $scope.items = [
        {id: 1, name: "Item 1"},
        {id: 2, name: "Item 2"},
        {id: 3, name: "Item 3"},
        {id: 4, name: "Item 4"}
    ];

    //initial value for select2
    $scope.select2 = $scope.items[0];    
});

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

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