【问题标题】:Set Selectedvalue in dropdown in AngularJS在 AngularJS 的下拉列表中设置 Selectedvalue
【发布时间】:2017-06-16 13:11:55
【问题描述】:

我正在使用 AngularJS。我正在尝试将下拉列表与响应中显示的值绑定。但我无法设置所选数据。它始终显示默认值。下面是index.cshtml:

<div class="col-sm-4">
   <select name="CopyseasonTypeSelect" ng-model="CopyselectedSeasonType" ng-options="CopySeason.SeasonTypeName for CopySeason in seasons">
        <option value="">-- Select the Season --</option>
   </select>
</div>

在controller.js中

testAPIService.getSeasonById(nId).success(function(response) {
    $scope.seasonByIdReponse = response;
    $scope.CopyselectedSeasonType = response.SeasonType;  // I am getting "Summer"
            $scope.init();        
    });
}

下拉列表的值是“-- 选择季节--”、“冬季”、“夏季”、“春季”

对象数组如下:

[object Object],[object Object],[object Object],[object Object]
   [
      0: {
         [functions]: ,
         $$hashKey: "object:78",
         __proto__: { },
         Id: 1,
         ImageUrl: "testicon.png",
         SeasonDetail: null,
         SeasonTypeName: "Winter"
      },
      1: { },
      2: { },
      3: { },
      length: 4
   ]

如何在服务的下拉菜单中设置值?

【问题讨论】:

  • 四季数组结构是什么?

标签: angularjs


【解决方案1】:
<select name="CopyseasonTypeSelect" 
        ng-model="CopyselectedSeasonType" 
        ng-options="i.SeasonTypeName as i.SeasonTypeName for i in seasons">
    <option value="" style="display: none">-- Select the Season --</option>
</select>

【讨论】:

  • 嗨@MeTe-30,我已经更新了初始代码块中的对象结构。我尝试了您的代码修复,但没有奏效。
  • 嗨@venkat14,response.SeasonType 到底是什么? “夏天”或 {Id: 2, SeasonTypeName : “夏天”}
  • response.seasontype 是服务返回的数据。我想将response.SeasonType设置为选中的数据,
  • @venkat14 我想知道response.seasontype的确切值
  • 值为“夏天”
【解决方案2】:

试试这个。在ng-options 中使用track by 对其进行初始化

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">

    <div class="container">
        <select name="CopyseasonTypeSelect" ng-model="CopyselectedSeasonType" ng-options="CopySeason.SeasonTypeName for CopySeason in seasons track by CopySeason.Id">
            <option value="">-- Select the Season --</option>
        </select>
    </div>
    <script>
        var app = angular.module("myApp", []);
        app.controller("myCtrl", function ($scope) {
            $scope.seasons = [{
                    SeasonTypeName: "Winter",
                    Id: 0
                },
                {
                    SeasonTypeName: "Summer",
                    Id: 1
                }, 
                {
                    SeasonTypeName: "Spring",
                    Id: 2
            }];
            
            $scope.CopyselectedSeasonType = $scope.seasons[1];
        });
    </script>

</body>

</html>

【讨论】:

  • 嗨@Nitheesh。我试过了,但是没有用。我更新了代码以显示对象数组的显示方式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多