【问题标题】:AngularJs dropdown values clearing out model valueAngularJs 下拉值清除模型值
【发布时间】:2014-02-27 02:15:05
【问题描述】:

我的下拉 html 如下所示:

<select name="originType" class="form-control"
        ng-model="myLocationType"
        ng-options="type.Key as type.Value for type in allLocationTypes"
        required></select>

这可以很好地填充下拉列表。但是,当我加载页面并用模型数据填充它时,应该选择的值永远不会是。下拉菜单始终使用默认(空白)值。我对不是键/值对的下拉列表没有任何问题。例如:

<select name="shipId" class="form-control"
        ng-model="WageAgreement.ShipId"
        ng-options="shipId for shipId in manufacturers"
        required></select>

【问题讨论】:

  • Angular 总是在选择中提供默认选项。当模型未定义时显示。如果您希望默认选项为其他内容,请为选择模型分配一个值。

标签: angularjs html-select


【解决方案1】:

如果模型值与数组中提供的值匹配,则填充模型值应该可以工作。请参阅http://jsfiddle.net/5qp54/2/,其中在设置为 WageAgreement.ShipId 的模型值时选择 2

var mod = angular.module("myApp", []);

mod.controller("MainController", function ($scope) {
    $scope.allLocationTypes = [
        {Key: 1, Value: "Shipyard 1"},
        {Key: 2, Value: "Shipyard 2"},
        {Key: 3, Value: "Shipyard 3"}
    ];
    $scope.WageAgreement = {};

    //Populate value here
    $scope.WageAgreement.ShipId = 2;
});

您的模型值是否与对象数组中的键匹配?如果没有选择下拉列表中的值,我怀疑某些内容不匹配。

如果这不能回答您的问题,您能否使用 jsfiddle 或您如何填充制造商/allLocations 和 WageAgreement 的示例更新您的帖子?

【讨论】:

  • 你是对的。密钥是一个 C# 枚举。该模型是使用 [JsonConverter(typeof(StringEnumConverter))] 返回的,这导致枚举以字符串形式返回,读取方式类似于枚举。通过直接获取枚举来填充下拉列表,这意味着该值被存储为整数。将其更改为使用枚举的字符串值,一切正常!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
相关资源
最近更新 更多