【问题标题】:select with a null value选择空值
【发布时间】:2014-12-04 22:54:13
【问题描述】:

是否可以正确呈现一个选择,其中一个值为空的几个选项?

我将提供一个简单的例子:

$scope.value = null;
$scope.list = [{ id: null, description: "none"},
    { id:1, description: "one" },
    { id:2, description: "two" },
    { id:3, description: "three" }];

html:

<select ng-model="value" ng-options="item.id as item.description for item in list">
</select>

Plunker:http://plnkr.co/edit/ECQ3XUnv75sJW4Ix8IyO

渲染后一切正常(没有选择),但是当我点击选择时,还有一个额外的选项 - 空(虽然$scope.valuenull,但“空”选项仍然存在)。当我选择其他选项并且$scope.value 不是null 时,一切似乎都正常。是否有某种方法可以删除模型为 null 时浏览器生成的空选项?

这种行为在 Firefox、Chrome 和 Safari 上是相同的。

【问题讨论】:

    标签: angularjs null html-select ng-options


    【解决方案1】:

    您不必手动添加无意义的空选项。您只需在 HTML 中添加空的option

    <select ng-model="value" ng-options="item.id as item.description for item in list">
        <option value="">none</option>
    </select>
    

    控制器:

    $scope.list = [
        { id:1, description: "one" },
        { id:2, description: "two" },
        { id:3, description: "three" }
    ];
    

    演示:http://plnkr.co/edit/8j9NUT3rUfwUj4QJhZqa?p=preview

    【讨论】:

    • 另外值得一提的是,这在文档中也有解释
    【解决方案2】:

    您可以使用undefined 而不是null 使其工作,并删除默认值的id 属性:

    angular.module('app', [])
    .controller('MainCtrl', function($scope) {
        $scope.value = undefined;
        $scope.list = [{ description: "none"},
            { id:1, description: "one" },
            { id:2, description: "two" },
            { id:3, description: "three" }]
    
    });
    

    【讨论】:

      猜你喜欢
      • 2012-05-04
      • 2018-08-04
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      相关资源
      最近更新 更多