How to have a default option in Angular.js select box

后端 未结 23 1539
悲哀的现实
悲哀的现实 2020-11-22 06:04

I have searched Google and can\'t find anything on this.

I have this code.


                        
    
提交评论

  • If you want to make sure your $scope.somethingHere value doesn't get overwritten when your view initializes, you'll want to coalesce (somethingHere = somethingHere || options[0].value) the value in your ng-init like so:

    <select ng-model="somethingHere" 
            ng-init="somethingHere = somethingHere || options[0].value"
            ng-options="option.value as option.name for option in options">
    </select>
    
    0 讨论(0)
  • 2020-11-22 06:32

    Only one answer by Srivathsa Harish Venkataramana mentioned track by which is indeed a solution for this!

    Here is an example along with Plunker (link below) of how to use track by in select ng-options:

    <select ng-model="selectedCity"
            ng-options="city as city.name for city in cities track by city.id">
      <option value="">-- Select City --</option>
    </select>
    

    If selectedCity is defined on angular scope, and it has id property with the same value as any id of any city on the cities list, it'll be auto selected on load.

    Here is Plunker for this: http://plnkr.co/edit/1EVs7R20pCffewrG0EmI?p=preview

    See source documentation for more details: https://code.angularjs.org/1.3.15/docs/api/ng/directive/select

    0 讨论(0)
  • 2020-11-22 06:33

    In my case since the default varies from case to case in the form. I add a custom attribute in the select tag.

     <select setSeletected="{{data.value}}">
          <option value="value1"> value1....
          <option value="value2"> value2....
           ......
    

    in the directives I created a script that checks the value and when angular fills it in sets the option with that value to selected.

     .directive('setSelected', function(){
        restrict: 'A',
        link: (scope, element, attrs){
         function setSel=(){
         //test if the value is defined if not try again if so run the command
           if (typeof attrs.setSelected=='undefined'){             
             window.setTimeout( function(){setSel()},300) 
           }else{
             element.find('[value="'+attrs.setSelected+'"]').prop('selected',true);          
           }
         }
        }
    
      setSel()
    

    })

    just translated this from coffescript on the fly at least the jist of it is correct if not the hole thing.

    It's not the simplest way but get it done when the value varies

    0 讨论(0)
  • 2020-11-22 06:34

    If you are using ng-options to render you drop down than option having same value as of ng-modal is default selected. Consider the example:

    <select ng-options="list.key as list.name for list in lists track by list.id" ng-model="selectedItem">
    

    So option having same value of list.key and selectedItem, is default selected.

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