Niranjan Godbole
Niranjan Godbole

Reputation: 2175

How to set default value to dropdownlist in angularjs

hi I am developing web application in angularjs. I have one dropdownlistbox with some values. Below is my dropdownlistbox html code.

<select id="calc-year" ng-model="period" name="period" required range-numberddwn="rangeddwn">
   <option value="" label="{{ 'Month' | translate }}">{{ 'Month' | translate }}</option>
   <option ng-repeat="x in cal" value="{{x.Period}}">{{x.Period}} {{'Months' | translate}}</option>
</select>

Below is my code to assign values to dropdownlistbox.

$scope.cal = response.data.data.Period;

Below is the screenshot of data i am assigning to cal.

Dropdown values

If i want to set 4th value by default then i tried as below.

$scope.period = $scope.cal[4]; and $scope.period = response.data.data.Period[4];

Whenever i set as above i blank value will come in dropdownlist

Above both options did not work out for me. May i know what is the solution to set default value? Any help would be appreciated. Thank you.

Upvotes: 0

Views: 1486

Answers (2)

Vivek Atri
Vivek Atri

Reputation: 56

In your controller, set a value in scope variable which you want to be the default value for your drop down. Make sure, cal variable exist in scope. Then try something like this,

$scope.calValue = $scope.cal[3]; //This will be Default cal value

Then in your view(html), use ng-options something like this,

<select ng-model="calValue" ng-options="x.Period for x in cal"></select>

Now, calValue will be the default value in drop down, and if you select any other option from dropdown, then that will become the value of calValue.

Cheers !!

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222702

If you want to set the 4th value index should be 3

 $scope.period = $scope.cal[3]; 
 $scope.period = response.data.data.Period[3];

Upvotes: 1

Related Questions