mitra p mitra p - 1 year ago 74
AngularJS Question

set a default value for the dropdown

This is my Java script code

$scope.dateSelection = { 1: 'Today' , 2: 'Yesterday' ,3: 'Last 7 days', 4: 'Last business week (Mon - Fri)' , 5: 'Last week (Sun - Sat)' , 6: 'This month' , 7: 'Last month' , 8: 'All time' , 9: 'CUSTOM_DATE',10: 'This week (Sun - Today)',11: 'This week (Mon - Today)' , 12: 'Last week (Sun - Sat)' };

This is my HTML code

<select ng-options="key as value for (key,value) in dateSelection track by key" ng-change="getPerformanceData(indexValue)" ng-model="indexValue" >

I want to set a default value is "3: 'Last 7 days'" for the dropdown.

Answer Source

You can also achieve the desired effect just by changing the HTML template.

    ng-init="indexValue = '3'"
    ng-options="key as value for (key,value) in dateSelection" 

You'll notice that I've removed the track by expression as it's mostly meant to help Angular internally with array sorting - and this is what was causing your problems as you're using an object and not an array.

I've also set the default value in the HTML template, but this can also be done in your controller, it's just a matter of preference.