AngularJS的选择空值 [英] AngularJS null value for select

查看:683
本文介绍了AngularJS的选择空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到一个&LT设置值一个优雅的方式;选择> 使用AngularJS。

I couldn't find an elegant way for setting null values with a <select> using AngularJS.

HTML

<select ng-model="obj.selected">
  <option value=null>Unknown</option>
  <option value="1">Yes</option>
  <option value="0">No</option>
</select>

{{obj}}

JS:

$scope.obj ={"selected":null};

在加载页面时,第一个选项被选中,这是很好的,并且输出 {选择:空} 。当第一个选项是有切换到另外一台后重新选择,输出变为 {选择:空} (带引号),这是不是我会期望。

When the page is loaded, the first option is selected, which is good, and the output is {"selected":null}. When that first option is reselected after having switch to another one, the output becomes {"selected":"null"} (with the quotes), which is not what I would expect.

运行例如:
http://plnkr.co/edit/WuJrBBGuHGqbKq6yL4La

我知道的标记&LT;期权价值= NULL&GT; 是不正确的。我也试图与&LT;期权价值=&GT; ,但它相当于一个空字符串,而不是空。所以没有选择第一个选项,它消失的另一种选择第一个选择是默认选中后。

I know that the markup <option value=null> is not correct. I also tried with <option value=""> but it corresponds to an empty String and not to null : the first option is therefore not selected and another option which disappears after the first selection is selected by default.

任何想法?

推荐答案

这应该为你工作:

控制器:

  function MyCntrl($scope) {
    $scope.obj ={"selected":null};
    $scope.objects = [{id: 1, value: "Yes"}, {id: 0, value: "No"}]
  }

模板:

  <div ng-controller="MyCntrl">

    <select ng-model="obj.selected"
            ng-options="value.id as value.value for value in objects">
            <option value="">Unknown</option>
    </select>

<br/>
     {{obj}}
  </div>

工作plnkr

您应该使用NG选项与选择。

You should use ng-options with select.

这篇关于AngularJS的选择空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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