Reputation: 1489
How to get selected value in angulajs when clicked on the button, im using the following code please suggest me?
<div class="form-inline">
<div class="form-group">
<select class="form-control" data-ng-model="selectedTimeZone">
<option data-ng-repeat-start="(key, value) in timeZoneData.countries" data-ng-bind="value.name"></option>
<option data-ng-repeat-end="" data-ng-repeat="tz in value.timezones" data-ng-bind="' - ' + tz"></option>
</select>
</div>
<div class="form-group">
<input id="btnAddTimeZone" type="button" value="Add Time Zone" class="btn btn-default" data-ng-click="populateTimeZone(selectedTimeZone)"/>
</div>
</div>
in Controller--
$scope.populateTimeZone = function (world_timezones) {
};
Json data--
{
"countries": {
"US": {
"id": "US",
"name": "United States",
"timezones": [
"America/New_York",
"America/Detroit",
]
},
"CA": {
"id": "CA",
"name": "Canada",
"timezones": [
"America/St_Johns",
"America/Halifax",
]
},
"IN": {
"id": "IN",
"name": "India",
"timezones": [
"Asia/Kolkata"
]
},
}
}
But im getting empty string.
Upvotes: 0
Views: 58
Reputation: 1743
From the AngularJS docs:
To bind the model to a non-string value, you can use one of the following strategies:
https://docs.angularjs.org/api/ng/directive/select
Option 1: Add ng-value
All you need to do is add an ng-value
to your options and it should work. You also might want to add a ng-disabled="true"
to your group headers so that it prevents the user from selecting "India" and not an actually timezone.
<option ng-repeat-start="(key, value) in timezones.countries" ng-bind="value.name" ng-disabled="true"></option>
<option ng-repeat-end="" ng-repeat="tz in value.timezones" ng-bind="' - ' + tz" ng-value="tz"></option>
Plunkr: https://next.plnkr.co/edit/l5H87H8k7Af5XIqH?open=lib%2Fscript.js&deferRun=1
Option 2: ng-options
with group by
Here's a possible solution using ng-options
on the select. You can still achieve a groupBy functionality grouping your timezones by country name.
HTML
<form>
<label>Timezone: </label>
<select class="form-control" ng-model="selectedTimezone" ng-options="tz.timezone group by tz.country for tz in timezones"></select>
</form>
<button class="btn btn-secondary" ng-click="populateTimeZone()">Add Timezone</button>
JavaScript
function MainCtrl($scope, MainService) {
$scope.selectedTimezone = undefined;
$scope.timezones = [];
MainService.loadTimezones().then(function(timezoneData){
$scope.timezones = Object.values(timezoneData.countries).flatMap(c => {
return c.timezones.map(tz => {
return {id: c.id, name: c.name, timezone: tz};
});
});
});
$scope.populateTimeZone = function(){
console.log('selectedTimezone', $scope.selectedTimezone);
};
}
Plunkr: https://next.plnkr.co/edit/Y4AVNU9X6MUAzckz?open=lib%2Fscript.js&deferRun=1
Upvotes: 1