【问题标题】:Angular JS select tag ng model gives one empty option IssueAngular JS 选择标签 ng 模型给出了一个空选项问题
【发布时间】:2016-10-10 04:00:47
【问题描述】:

使用 ng-model 和 ng-options 属性我绑定了 select html 标签。 它正确绑定选项中的所有数据,但一个空选项首先与“”绑定。 我想使用 angular 删除这个空选项

<select class="ng-pristine UserGroups selectGroupClass"  ng-model='groupList' required ng-options='item.name for item in groupOptions track by item.name'></select>

$scope.groupOptions = [{ name: "What's Hot", value: 'latest' }, { name: 'Trending', value: 'popular' }];

【问题讨论】:

  • groupOptions 是什么样子的

标签: angularjs


【解决方案1】:

当 ng-model 引用的值在传递给 ng-options 的一组选项中不存在时,将生成空选项。

如果您想使用 angular 删除这个空选项,请在控制器中选择一个初始值,

$scope.groupList = $scope.groupOptions[0];

请检查工作示例:Here

你可以添加

<option style="display:none" value="">select a type</option>

在 HTML 中

<select class="ng-pristine UserGroups selectGroupClass"  ng-model='groupList' required ng-options='item.name for item in groupOptions track by item.name'>
  <option ng-hide="true" value="">Select a Type</option>
</select>

请在此处查看工作示例:Demo for 2nd option

【讨论】:

    【解决方案2】:

    track by 只是帮助 Angular 在内部进行数组排序并防止数组中的重复项。选项的值由第一个参数(在您的案例项目中)定义。如果你希望它是 id 那么你应该使用 item 作为 groupOptions 中项目的 item.name

    【讨论】:

    • 你能提供更多代码吗?要在选择标签中显示的对象
    【解决方案3】:

    其中一个项目的名称是空白的,这是我能想到的!如果可能的话,只需验证一下。如果可能的话,使用 item.someOtherproperty 来调试它:)

    【讨论】:

      【解决方案4】:

      试试这个解决方案

         <select ng-model="selected" ng-options="item as item.name for item in groupOptions">
          <option value="">Choose</option>}
         </select>
      <div data-ng-bind="selected.name"></div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-28
        • 1970-01-01
        • 2019-04-27
        • 2019-01-24
        • 2014-10-12
        • 1970-01-01
        • 2019-06-18
        • 1970-01-01
        相关资源
        最近更新 更多