Sampath
Sampath

Reputation: 65870

Change the drop down selected value from an angular controller

I need to change the "selected value" of the drop down from the already saved value in db. How can I do that?

Controller

var app = angular.module('app', []);

app.controller('ctrl', function($scope) {
  $scope.months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

  $scope.selected='August';//here it's not working ?
});

HTML

<html ng-app="app">
  <body ng-controller="ctrl">
<div class="sample" align="center">
  <h1>AngularJS Combobox</h1>
<select ng-model="selected" ng-options="opt as opt for opt in months" ng-init="selected='March'"></select>
  <h3>You have selected : {{selected}}</h3>
</div>
    </body>
</html>

My CODE PEN is here.

Any help would be highly appreciated.

Upvotes: 1

Views: 2823

Answers (2)

Shawn Erquhart
Shawn Erquhart

Reputation: 1858

To set the initial selected default: set via $scope.selected in the controller - don't use ng-init for this.

To reset the default after a database save, you'll want to use a promise for the save operation and reset the select field in the promise's return function.

Upvotes: 1

JSK NS
JSK NS

Reputation: 3446

Remove the:

ng-init="selected='March'"

So that your new view code is as follows:

<html ng-app="app">
  <body ng-controller="ctrl">
<div class="sample" align="center">
  <h1>AngularJS Combobox</h1>
<select ng-model="selected" ng-options="opt as opt for opt in months"></select>
  <h3>You have selected : {{selected}}</h3>
</div>
    </body>
</html>

Upvotes: 2

Related Questions