【问题标题】:How can I fix sorting in angularjs select box and set selected item?如何修复 angularjs 选择框中的排序并设置所选项目?
【发布时间】:2014-05-29 09:10:38
【问题描述】:

我正在尝试使用月份列表制作 angularjs 选择框。

我从服务器传递月份名称列表(我使用 C#)

首先我试着像字典一样过几个月:

var months = new Dictionary<int, string>
{
  {1, Strings.January}, {2, Strings.February}, {3, Strings.March}, 
  {4, Strings.April}, {5, Strings.May}, {6, Strings.June}, 
  {7, Strings.July}, {8, Strings.August}, {9, Strings.September}, 
  {10, Strings.October}, {11, Strings.November}, {12, Strings.December}
};

我的选择看起来像这样:

<select class="form-control" ng-model="period.StartMonth" ng-options="value for (key, value) in model.Months track by key">
</select>

在这种情况下,选择会填充月份,但是!我这里有 2 个问题,我怀疑它们是相关的:

  1. 我的月份列表排序错误。它按键排序,就好像键是一个字符串,而不是一个整数。首先是 1 月,然后是 10 月、11 月等。

  2. 未选择任何值。我指定了“按键跟踪”,但显然因为它假设键是字符串,所以它忽略了存储在 period.StartMonth 中的整数值。当我尝试设置“按值跟踪”并设置 ng-model="period.StartMonthName" 时,该值被选中。但这不是我想要的样子。

我也尝试过几个月作为列表,但我仍然得到错误的排序。

有什么想法可以向 angularjs 解释我的键是整数并修复排序/设置所选项目吗?

【问题讨论】:

    标签: c# angularjs


    【解决方案1】:

    试试这个方法。

    以这种格式创建您的月份。

    $scope.months = [{id:1, name :"January"},{id:2, name :"February"},
                    {id:3, name :"March"},{id:4, name :"April"},
                    {id:5, name :"May"},{id:6, name :"June"},
                    {id:7, name :"July"},{id:8, name :"August"},
                    {id:9, name :"September"},{id:10, name :"October"},
                    {id:11, name :"November"},{id:12, name :"December"}];
    

    在你的 html 中

       <select id="month" name="month" ng-model="period.StartMonth" 
             ng-options="month.id as month.name for month in months"></select>
    
         selected month id = {{period.StartMonth}} 
    

    【讨论】:

    • 谢谢!有用。但无论如何,我想知道是否有可能以某种方式使用从服务器传递的字典。 angular 为字符串使用整数键并破坏正确的排序似乎很奇怪。
    • 我不认为字典是按其实现排序的。如果这是正确的,您不能期望月份会按照您的意愿列出。
    • 至少 angular 在没有被要求的时候不能进行排序 =)
    【解决方案2】:

    尝试为您的键添加尾随零。

    排序:

    var months = new Dictionary<int, string>
        {
            {01, Strings.January}, {02, Strings.February}, {03, Strings.March}, 
            {04, Strings.April}, {05, Strings.May}, {06, Strings.June}, 
            {07, Strings.July}, {08, Strings.August}, {09, Strings.September}, 
            {10, Strings.October}, {11, Strings.November}, {12, Strings.December}
        };
    

    选择
    2.当你选择月份时,要么传递整个对象,如:{01, "January"} 并设置 ng-model="period.StartMonth.id" 或使 period.StartMonth 等于所选的 id ( 01 )目的。总之,ng-model 的值必须与您提供给 ng-options 的列表中的一个 id 匹配。

    【讨论】:

    • 然后按照 Matthews 的建议,使用对象数组而不是字典。这会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    相关资源
    最近更新 更多