javascript Angular ng-options 删除空白选项并仅选择第一个选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30104565/
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-10-28 11:40:53  来源:igfitidea点击:

Angular ng-options remove blank option and select the first option only

javascriptangularjshtmlng-options

提问by Ankit Tanna

I am using AngularJS to populate my select options content dynamically from an array of objects in my controller. My objects has a property named userProfileName.

我正在使用 AngularJS 从控制器中的对象数组动态填充我的选择选项内容。我的对象有一个名为userProfileName的属性。

How would it be possible to remove the blank option that I am getting at the top?

怎么可能删除我在顶部得到的空白选项?

Also, I would want to select the first profile Profile 1by default. How can this be done?

另外,我想默认选择第一个配置文件Profile 1。如何才能做到这一点?

My Snippet of code is here:

我的代码片段在这里:

<select id="requestorSite" 
                             ng-model="selectedUserProfile"
                             ng-options="userProfile.userProfileName for userProfile in userProfiles"
                             ng-selected=""
                             class="form-control displayInlineBlock width40per marginLeft15">
                            </select>

My controller has

我的控制器有

$scope.userProfiles

As the array of object and each object has userProfileNameattribute.

作为对象数组,每个对象都有userProfileName属性。

Below is the screen shot: enter image description here

下面是屏幕截图: 在此处输入图片说明

I would like to remove the blank option at the top and also have by default Profile 1selected.

我想删除顶部的空白选项,并默认选择配置文件 1

Thanks, Ankit

谢谢,安吉特

回答by carton

Do this :)

做这个 :)

In your controller :

在您的控制器中:

 function myCtrl ($scope) {
   $scope.userProfiles = [
     {id: 10, name: 'Carton'},
     {id: 27, name: 'Bernard'},
     {id: 39, name: 'Julie'},
  ];

   $scope.selectedUserProfile= $scope.userProfiles[0]; // Set by default the   value "carton"
  };

In your page :

在您的页面中:

      <select  id="requestorSite" ng-model="selectedUserProfile" ng-options="userProfile as userProfile.name for userProfile in userProfiles">
            </select>

CodePen: http://codepen.io/anon/pen/qdOGVB

代码笔:http://codepen.io/anon/pen/qdOGVB

回答by Hari Das

This has several solution. The following worked best for me. Just initialize the model with the first value. The ng-init="myItem = items[0].name"does the trick

这有几个解决办法。以下对我来说效果最好。只需使用第一个值初始化模型。该ng-init="myItem = items[0].name"做的伎俩

<select ng-if="items" ng-init="myItem = items[0].name" ng-model="myItem">
     <option ng-repeat="item in items" ng-value="item.name">{{item.name}}</option>
</select>