Reputation: 801
I have a dropdown in angularJS defined as:
$scope.Ids = [ {
id : 'ID-100',
name : 'ID-100'
}, {
id : 'ID-200',
name : 'ID-200'
}, {
id : 'ID-300',
name : 'ID-300'
} ];
$scope.Id = $scope.Ids[0];
<select class="custom-select" ng-model="Id" ng-options="choice.name for choice in Ids"></select>
My requirement is to dynamically populate these Ids from DB.
I have a spring controller that makes a call to DB:
$http({
'url' : '/getIds',
'method' : 'POST',
'headers' : {
'Content-Type' : 'application/json'
},
'params' : data
}).then(function(response) {
$scope.Ids = response.data.Ids;
});
and yields a list:
["ID-100", "ID-200", "ID-300"]
0: "ID-100"
1: "ID-200"
2: "ID-300"
My $scope.Ids will now be having the new list. I need to map this list to my $scope.Ids
in dropdown format and make my dropdown display the first record.
Can someone give an idea on how to achieve this?
Upvotes: 0
Views: 1641
Reputation: 222522
Your code is already correct, however your approach should be like below.
DEMO
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope",
function($scope) {
$scope.Ids = [{
id : 'ID-100',
name : 'ID-100'
}, {
id : 'ID-200',
name : 'ID-200'
}, {
id : 'ID-300',
name : 'ID-300'
}];
$scope.Id = $scope.Ids[0];
}]);
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="dobController">
<select class="custom-select" ng-model="Id" ng-options="choice.name for choice in Ids"></select>
<div>
<h1> Selected one is : {{Id}} </h1>
</div>
</body>
</html>
Upvotes: 1