首页 > 解决方案 > 动态填充下拉列表 - AngularJS

问题描述

我在 angularJS 中有一个下拉列表,定义为:

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

我的要求是从 DB 中动态填充这些 Id。

我有一个调用 DB 的 spring 控制器:

$http({
                        'url' : '/getIds',
                        'method' : 'POST',
                        'headers' : {
                            'Content-Type' : 'application/json'
                        },
                        'params' : data
                    }).then(function(response) {
                        $scope.Ids = response.data.Ids;
                    });

并产生一个列表:

["ID-100", "ID-200", "ID-300"]
0: "ID-100"
1: "ID-200"
2: "ID-300"

我的 $scope.Ids 现在将拥有新列表。我需要将此列表映射到我$scope.Ids的下拉格式并让我的下拉列表显示第一条记录。

有人可以就如何实现这一目标提出一个想法吗?

标签: angularjs

解决方案


您的代码已经正确,但是您的方法应该如下所示。

演示

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>


推荐阅读