how to use ng-option to set default value of select element

前端 未结 12 638
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 11:07

I\'ve seen the documentation of the Angular select directive here: http://docs.angularjs.org/api/ng.directive:select. I can\'t figure how to set the default value. This is

相关标签:
12条回答
  • 2020-11-22 11:47

    Really simple if you do not care about indexing your options with some numeric id.

    1. Declare your $scope var - people array

      $scope.people= ["", "YOU", "ME"];
      
    2. In the DOM of above scope, create object

      <select ng-model="hired" ng-options = "who for who in people"></select>
      
    3. In your controller, you set your ng-model "hired".

      $scope.hired = "ME";
      

    Good luck!!! It's really easy!

    0 讨论(0)
  • 2020-11-22 11:48
    <select name='partyid' id="partyid" class='span3'>
    <option value=''>Select Party</option>
    <option ng-repeat="item in partyName" value="{{item._id}}" ng-selected="obj.partyname == item.partyname">{{item.partyname}}
    </option>
    </select>
    
    0 讨论(0)
  • 2020-11-22 11:50

    This answer is more usefull when you are bringing data from a DB, make modifications and then persist the changes.

     <select  ng-options="opt.id as opt.name for opt in users" ng-model="selectedUser"></select>
    

    Check the example here:

    http://plnkr.co/edit/HrT5vUMJOtP9esGngbIV

    0 讨论(0)
  • 2020-11-22 11:58

    If your array of objects are complex like:

    $scope.friends = [{ name: John , uuid: 1234}, {name: Joe, uuid, 5678}];
    

    And your current model was set to something like:

    $scope.user.friend = {name:John, uuid: 1234};
    

    It helped to use the track by function on uuid (or any unique field), as long as the ng-model="user.friend" also has a uuid:

    <select ng-model="user.friend" 
    ng-options="friend as friend.name for friend in friends track by friend.uuid"> 
    </select>
    
    0 讨论(0)
  • 2020-11-22 11:58
    <select id="itemDescFormId" name="itemDescFormId" size="1" ng-model="prop" ng-change="update()">
        <option value="">English(EN)</option>
        <option value="23">Corsican(CO)</option>
        <option value="43">French(FR)</option>
        <option value="16">German(GR)</option>
    

    Just add option with empty value. It will work.

    DEMO Plnkr

    0 讨论(0)
  • 2020-11-22 11:59

    An easier way to do it is to use data-ng-init like this:

    <select data-ng-init="somethingHere = options[0]" data-ng-model="somethingHere" data-ng-options="option.name for option in options"></select>
    

    The main difference here is that you would need to include data-ng-model

    0 讨论(0)
提交回复
热议问题