Javascript 使用 AngularJS 选择的占位符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42766564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:25:21  来源:igfitidea点击:

Placeholder for select with AngularJS

javascripthtmlcssangularjs

提问by user441521

I can't get a placeholder idea with select. With the below the first entry is still blank.

我无法通过选择获得占位符的想法。下面的第一个条目仍然是空白的。

<select class="form-control" ng-model="refData" required>
     <option ng-repeat="d in refData">
          {{d.value}}
     </option>
     <option value="" disabled hidden selected>View current values</option>
</select>

回答by lin

You can use transclusion to add an extra option that is disabled and selected. See How do I make a placeholder for a 'select' box?for more background on that general solution. Here is the ngSelect documentationfor reference, as well.

您可以使用嵌入来添加一个被禁用和选中的额外选项。请参阅 如何为“选择”框制作占位符?有关该通用解决方案的更多背景信息。这里也是ngSelect 文档供参考。

View

看法

<div ng-controller="MyCtrl">
    <select name="mySelect" 
            id="mySelect"
            ng-options="option.name for option in refData track by option.id"
            ng-model="selectedOption">
         <option value="" disabled selected>View current values</option>
     </select>
</div>

AngularJS application

AngularJS 应用

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.refData = [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ];

    $scope.selectedOption =  "";
});

JsFiddle Demo

JsFiddle 演示

回答by Nehal Soni

<select ng-model="testData" ng-options="test.name for test in testData">
        <option value="" selected>View current values</option>
</select>

Given test data is:

给定的测试数据是:

$scope.testData = [{"name" : "John"}, {"name" : "Micheal"}, {"name" : "Sarah"}];

回答by necilAlbayrak

I suggest using ng-options

我建议使用 ng-options

<select ng-options="d as d.value for d in refData" ng-model="refDataSelected"></select>

On your controller you can declare

在您的控制器上,您可以声明

$scope.refDataSelected = refData[0]

$scope.refDataSelected = refData[0]

to use first element as default option

使用第一个元素作为默认选项

If you want to create a dummy text you can add a new object to refData with custom text and give it an unreal id like -1. But when you submit you should check whether its id is -1 or not.

如果你想创建一个虚拟文本,你可以使用自定义文本向 refData 添加一个新对象,并给它一个像 -1 这样的虚幻 id。但是当您提交时,您应该检查它的 id 是否为 -1。