AngularJS ng-repeat setting default select value

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

$scope.activities =     [         { id: 1, type: "DROPDOWN_MENU", name: "Dropdown Menu" },         { id: 2, type: "HORIZONTAL_BAR", name: "Horizontal Bar" }     ];  <select data-ng-model="engineer.currentActivity" data-ng-options="a.name for a in activities">                 </select>

Using the above I am able to create a select box with 3 values, a blank one and then dropdown menu and horizontal bar.

I would like to set Horizontal Bar as my default and cannot see how to do this.

Help would be great

回答1:

In the controller, just add a line to setup the initial selection:

$scope.activities =     [         { id: 1, type: "DROPDOWN_MENU", name: "Dropdown Menu" },         { id: 2, type: "HORIZONTAL_BAR", name: "Horizontal Bar" }     ];  $scope.engineer = {}; // if needed $scope.engineer.currentActivity = $scope.activities[1];


回答2:

In your angular controller:

$scope.activities = [     { id: 1, type: "DROPDOWN_MENU", name: "Dropdown Menu" },     { id: 2, type: "HORIZONTAL_BAR", name: "Horizontal Bar" } ]; $scope.activity = $scope.activities[1]; //Bind 2nd activity to the model.

In the HTML:

<select ng-model="activity"      ng-options="activity as activity.name for activity in activities">     <option value=""></option> </select>

See the Fiddle



回答3:

Use ng-init directive

ng-init="engineer.currentActivity = options[1]"


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