search

Home  >  Q&A  >  body text

angular.js - How to add default displayed options in dropdown list in angularjs?

The dom result is as follows, which is a drop-down list for height selection

<select ng-model="selectedHeight" ng-options="obj.h for obj in heights"></select>

Pass a height array to heights in the controller

$scope.heights=[{"h":"140cm"},{"h":"141cm"}];

During initialization, the drop-down list needs to display the first 140cm option. How can I display the first option?

Exploration:
In the current situation, it is useless to use $scope.selectedMonth = $scope.months[0].value; directly. We need to add a value to the array

$scope.heights=[{"h":"140cm","value":0},{"h":"141cm","value":1}];

At the same time, during two-way binding, bind the value in

<select ng-model="selectedMonth" ng-options="obj.value as obj.h for obj in heights"></select>

In this case, you can initialize the display

$scope.selectedMonth = $scope.months[0].value; 

Supplement: Note that when defining ng-options, you cannot add value, otherwise you will not be able to get the value of the option in the controller

<select ng-model="selectedMonth" ng-options="obj as obj.h for obj in heights"></select>

Reference:
Link Description

黄舟黄舟2813 days ago586

reply all(1)I'll reply

  • PHPz

    PHPz2017-05-15 16:57:59

    Initialize in controller:

        $scope.selectedHeight = $scope.heights[0].h;

    reply
    0
  • Cancelreply