【问题标题】:Dynamically populate dropdown - AngularJS动态填充下拉列表 - AngularJS
【发布时间】:2019-06-06 16:16:42
【问题描述】:

我在 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


    【解决方案1】:

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

    演示

    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>

    【讨论】:

    • Sajeetharan,请查看更新后的问题。我添加了 spring 控制器调用部分。我在尝试 $scope.Id.id 时收到错误“无法读取未定义的属性 'id'”
    • @Mike 听起来您正在尝试使用错误的属性。当您从 http 请求 $scope.Ids = response.data.Ids 设置 $scope.Ids 时,它会将 Ids 设置为您从数据库中获得的内容,并且您的数据库响应中没有 id 属性。在这种情况下,由于您的响应是字符串数组,而不是对象,您将无法查看下拉选项以及 Sajeetharan 给定的解决方案。
    • 是的蚕儿。这就是我需要的。我需要了解如何更改它以获取下拉菜单,就像默认下拉菜单一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2020-06-26
    • 2015-12-11
    • 2014-03-01
    • 1970-01-01
    • 2011-12-09
    相关资源
    最近更新 更多