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

☆樱花仙子☆ 提交于 2019-12-19 09:42:30

问题


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.

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 1 by default. How can this be done?

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 userProfileName attribute.

Below is the screen shot:

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

Thanks, Ankit


回答1:


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




回答2:


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

<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>


来源:https://stackoverflow.com/questions/30104565/angular-ng-options-remove-blank-option-and-select-the-first-option-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!