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

时间:2015-05-07 14:49:34

标签: javascript angularjs html5 ng-options

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

如何删除我在顶部获得的空白选项?

另外,我想默认选择第一个配置文件配置文件1 。怎么办呢?

我的代码片段在这里:

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

我的控制器

$scope.userProfiles

由于对象数组和每个对象都有 userProfileName 属性。

以下是截图: enter image description here

我想删除顶部的空白选项,默认选择个人资料1

谢谢, ANKIT

2 个答案:

答案 0 :(得分:11)

这样做:)

在您的控制器中:

 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"
  };

在您的信息页中:

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

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

答案 1 :(得分:0)

这有几个解决方案。以下对我来说效果最好。只需使用第一个值初始化模型。 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>