ngplayground
ngplayground

Reputation: 21667

AngularJS ng-repeat setting default select value

$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

Upvotes: 3

Views: 19058

Answers (3)

RaviH
RaviH

Reputation: 3584

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

Upvotes: 3

Davin Tryon
Davin Tryon

Reputation: 67326

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];

Upvotes: 4

StarsSky
StarsSky

Reputation: 6711

Use ng-init directive

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

Upvotes: 0

Related Questions