如何将自定义选项添加到ng选项输出中

How to add custom option to ng-options output?

本文关键字:选项 ng 输出 添加 自定义      更新时间:2023-09-26

我在一个表中创建了一个select,从列表中获取一些电子邮件地址。这是代码:

<td>
    <select ng-init="selectedEmail = selectedEmail ? selectedEmail : emails[0]" class="form-control" ng-model="selectedEmail" ng-options="item as item.dest for item in emails"></select>
</td>

我会添加一个额外的选项,这将是最终用户的自定义选项。如果我在<select>中添加<option>,它将被Angular ng-options 覆盖

<td>
    <select ng-init="selectedEmail = selectedEmail ? selectedEmail : emails[0]" class="form-control" ng-model="selectedEmail" ng-options="item as item.dest for item in emails">
        <option value="custom">Custom</option>
    </select>
</td>

如何添加自定义选项?

我的目的是为用户添加一个"自定义"选项:如果他们选择了这个选项,他们可以写下自己的选择,一个自定义文本。

您可以按照以下操作:

<div ng-controller="TestController">
  {{sel}}
  <select ng-model="sel" ng-options="d.value as d.label for d in data">
    <option value="">any</option>
  </select>
</div>

也可以看到这个小提琴

有几种方法可以解决这个问题。如果您想继续使用ng-options,可以使用一个函数。

HTML

<td>
    <select 
        ng-init="selectedEmail = selectedEmail ? selectedEmail : emails[0]"
        class="form-control" 
        ng-model="selectedEmail" 
        ng-options="item as item.dest for item in BuildList()"></select>
</td>
<input type="text" placeholder="Enter Custom Option" ng-model="customText" />

BuildList的控制器功能

$scope.BuildList = function() {
    if(!$scope.customText) {
       return $scope.emails;
    }
    var newList = angular.copy($scope.emails);
    newList.push({someobjectbuildUsingCustom});
    return newList ;
}

您可以使用以下语法:

<select>
    <option ng-repeat="(key, value) in emails" value="{{key}}">{{value}}</option>
    <option ... custom option ...>...</option>
</select>