How to make a preselection for a select list generated by AngularJS?

后端 未结 5 1846
天命终不由人
天命终不由人 2020-11-29 07:57

This correctly creates a select list

相关标签:
5条回答
  • 2020-11-29 08:46

    Here's an alternate method for initializing a drop down menu using AngularJS.

    (working example on JS Fiddle: http://jsfiddle.net/galeroy/100ho18L/1/)

    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    </head>
    
    <body ng-app="" ng-controller="myController">
    
        <select 
            ng-model="carSelection"
            ng-options = "x.make for x in cars">
        </select>
    
        <script>
    
            function myController($scope) {
    
                $scope.cars = [
                    {"make": "Nissan", "model": "Sentra"},
                    {"make": "Honda", "model": "Prelude"},
                    {"make": "Toyota", "model": "Prius"}
                ]
    
                $scope.carSelection = $scope.cars[1]; // this line initializes the drop down menu
            }
    
        </script>
    
    </body>
    

    0 讨论(0)
  • 2020-11-29 08:48

    I achieved this using ng-model and ng-options.Basically your model and ng-options should be in sync.

    When my model (projIndustry in this case) was initialized to some number then I had to use ind.ID in ng-options.(ID comparison).
    When my model was initialized to object ,then I had to use ind(object) in ng-options.(Object comparison)

    <select data-ng-options="ind.ID as ind.Display_Text for ind in arrIndustries" 
     data-ng-model="projIndustry" ng-change="onIndChange()" />
    
    0 讨论(0)
  • 2020-11-29 08:50

    Here's what worked:

    <select ng-init="team.captain=team.players[0]" 
            ng-model="team.captain" 
            ng-options="player.name for player in team.players"></select>
    

    And what didn't work:

    ng-init="team.captain='0'"
    ng-init="team.captain='John'"
    

    My guess is that Angular goes beyond simple comparison of values or labels. It probably compares object references.

    0 讨论(0)
  • 2020-11-29 08:57

    As @camus already mentioned in a comment, you need to set the model to a valid "label" value (or reference), not an index value. This is a bit odd since you can see an index value being used in the HTML.

    Angular sets the value attributes in the HTML as follows:

    • when using array as datasource, it will be the index of array element in each iteration;
    • when using object as datasource, it will be the property name in each iteration.

    When an item is selected, Angular looks up the correct entry in the array/object based on the index or property name.

    0 讨论(0)
  • 2020-11-29 09:00

    What about ng-selected, as seen in this jsfiddle:

    <select ng-model="val">
      <option ng-repeat="opt in options" ng-selected="$first">
        {{ opt }}
      </option>
    </select>
    
    0 讨论(0)
提交回复
热议问题