AngularJS ng-options在选择选项后删除了默认空白值 [英] AngularJS ng-options removed default blank value after selecting an option

查看:82
本文介绍了AngularJS ng-options在选择选项后删除了默认空白值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将ng-options用于我的select标签,以便为用户提供选择.一切工作正常,但首次选择选项后,默认的空白值消失了.如果我想再次还原为默认空白值怎么办?那怎么办?如何保留该空白值?

I am using ng-options for my select tag to have choices for the users. Everything works perfectly but after selecting an option for the first time the default blank value is gone. What if I want to revert back to the defaul blank value again? How can that be done? How can I retain that blank value?

这是我的代码示例:

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  </head>

  <body ng-controller="myController">
    <h1>Hello World!</h1>
    <select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions">

    </select>
  </body>

</html>

<script>
  var app = angular.module('app', []);
  app.controller('myController', function($scope){
    $scope.myOptions = [{
      "value": null,
      "label": null,
    },{
      "value": "First",
      "label": "First",
    },{
      "value": "Second",
      "label": "Second",
    },{
      "value": "Third",
      "label": "Third",
    }]
  });
</script>

这里是the人: http://plnkr.co/edit/5f17YxRfWFI4g40t3NEf?p=preview

推荐答案

使用

<select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions">
    <option value=""></option>
  </select>

请勿使用虚拟null对象污染您的"myOptions",因为API不会返回相同的结果.您需要在表示层上进行处理,如上所示.保存时,如果use选择为空,则将其保存为null(如果处理正确)

Don't pollute your 'myOptions' with dummy null object, as APIs will not return you the same. you need to handle it on presentation layer, as shown above. while saving, if use selects empty, it will be saved as null (if handled properly)

你也可以有这样的东西

<option value="">---select---</option>

这篇关于AngularJS ng-options在选择选项后删除了默认空白值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆