简体   繁体   中英

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.

下拉值

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.

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

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

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 !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM