Abderrahim Abderrahim - 7 months ago 13
HTML Question

A default choice in my select in angular JS

I am using AngularJS to create a simple application web.

I would like to show the values of city A as a default choice in my select.

index.html

<body ng-controller="MainCtrl">
<select ng-model="selectedCity" ng-change="extractSubsities(selectedCity)" ng-options="item as item.name for item in cities track by item.name">
</select>

<select ng-show="selectedCity.subsities" ng-model="selectedSubCity" ng-change="extractSubsities(selectedSubCity)" ng-options="item2 as item2.name for item2 in selectedCity.subsities track by item2.name">
<option style="" value=""></option>
</select>

<table>
<tr ng-repeat="item3 in data track by item3.id">
<td>{{ item3.id }}</td>
<td>{{ item3.name }}</td>
<td>{{ item3.price }}</td>
</tr>
</table>

</body>

</html>


And this is my script js:

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

app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.cities = [
{
name: "city A",
elements: [{
id: 'c01',
name: 'name1',
price: 15
}, {
id: 'c02',
name: 'name2',
price: 18
}, {
id: 'c03',
name: 'name3',
price: 11
}],
subsities: [ {
name: "sub A1",
elements: [{
id: 'sub01',
name: 'nameSub1',
price: 1
}, {
id: 'sub02',
name: 'nameSub2',
price: 8
}, {
id: 'sub03',
name: 'nameSub3',
price: 1
} ]
},
{
name: "sub A2",
elements: [{
id: 'ssub01',
name: 'nameSsub1',
price: 1
}, {
id: 'ssub02',
name: 'nameSsub2',
price: 8
}, {
id: 'ssub03',
name: 'nameSsub3',
price: 4
} ]
},
{
name: "sub A3",
elements: [{
id: 'sssub01',
name: 'nameSssub1',
price: 1
}, {
id: 'sssub02',
name: 'nameSssub2',
price: 2
}, {
id: 'sssub03',
name: 'nameSssub3',
price: 1
}]
}
]
},
{
name: "city B",
elements: [{
id: 'cc01',
name: 'name11',
price: 10
}, {
id: 'cc02',
name: 'name22',
price: 14
}, {
id: 'cc03',
name: 'name33',
price: 11
} ]
},
{
name: "city C",
elements: [{
id: 'ccc01',
name: 'name111',
price: 19
}, {
id: 'ccc02',
name: 'name222',
price: 18
}, {
id: 'ccc03',
name: 'name333',
price: 10
} ]
}
];
$scope.extractSubsities = function(itemSelected) {
if(itemSelected && itemSelected.elements){
$scope.data = itemSelected.elements;
}
}

});


I need to show city A as the default selected value How can I fix this please ?

Answer

You can use the ng-init directive to initialize your selection. Also you will have to call your extractSubsities() function to populate your table:

 <select ng-model="selectedCity"  ng-change="extractSubsities(selectedCity)" ng-options="item as item.name for item in cities track by item.name" ng-init="selectedCity = cities[0];extractSubsities(selectedCity)">
  </select>

here is a working fiddle example