使用 ng-model 删除 select 中的空选项

Remove empty option in the select using ng-model

我是 angular js 的新手。在我的代码中,用户更改了单选按钮的值。并根据 selected 单选按钮的值,从 ng-switch
加载一段代码 HTML:

<body ng-app="">
  <div ng-repeat="button in modes">
    <label>
      <input type="radio" ng-model="data.mode" value="{{button.value}}" ng-click="clearObjectIdModal()" name="e_modes">
        {button.label}}
    </label>
  </div>

  <div ng-switch on="data.mode">

    <div ng-switch-when="client">
      <label for="e_selected_object_item_id">Select Client name: </label>
      <select id="e_selected_object_item_id" name="e_selected_object_item_id" ng-model="currentDataItem.object_id" required>
        <option ng-repeat="item in customersListArr" value="{{ item.id }}">{{ item.Name }}</option>
      </select>
    </div>

   <div ng-switch-when="agent">
     // This part is similar to the previous one
   </div>

  </div>
</body>

控制器部分:

$scope.data = {};
$scope.setFile = function () {
  if ($scope.data.mode == 'client')
    return 'client';
  else if ($scope.data.mode == 'agent')
    return 'agent';

$scope.modes = [{
  value: 'client',
  label: 'Client'
},{
  value: 'agent',
  label: 'Agent'
}];

$scope.currentDataItem = data;  // data is preloaded from inputs in form

还有一个ng-click="clearObjectIdModal()"切换单选按钮时清除模型:

$scope.clearObjectIdModal = function() {
  $scope.currentDataItem = "";
}

问题是每次单选按钮切换到动态变化的select值时,其中第一个选项的值变为等于undefined。因为在构建这些选项的数组中没有这样的object_id(这是不存在的id,所以绘制了一个空字段)。
也就是说,有所有的作品。但是 select 中的第一个选项(切换到另一个单选按钮后)呈现为空字符串。
有想法,怎么解决?

我不确定我是否正确理解你的问题,但我会提出一些改进建议。

  1. 将您的 setFile 函数更改为如下

    $scope.setFile = 函数 (){return $scope.data.mode;}

我也没有在代码中看到函数的右括号。此外,如果您的功能只会 return data.mode 那么为什么需要该功能?

  1. 我建议正确初始化您的 data 对象,例如:

    $scope.data = {模式:'client'};

  2. 将您的 clearObjectIdModal 函数更改为:

    $scope.clearObjectIdModal = 函数(模式) { $scope.currentDataItem = ""; $scope.data.mode=模式; }

并在您的 HTML 中将其用作 ng-click="clearObjectIdModal(button.mode)"

所以在函数 clearObjectIdModal() 中我写道:

$scope.clearObjectIdModal = function() {
  if ($scope.e_data["mode"] == 'client') {
    if ($scope.customersListArr.length > 0) {
      $scope.currentDataItem.object_id = $scope.customersListArr[0]['id'];
    }
  }
  else if ($scope.e_data["mode"] == 'agent') {
    if ($scope.agentsListArr.length > 0) {
      $scope.currentDataItem.object_id = $scope.agentsListArr[0]['id'];
    }
  }

}

之后,当我更改单选按钮时,当前 select(每次更改)中的第一个选项将不为空。

当您将标题添加为列表中的第一项时,额外的空选项的问题也可以解决:

<option value="" disabled>Select</option>