【问题标题】:orderBy Angular order by specific propertyorderBy 特定属性的角度顺序
【发布时间】:2015-11-10 17:02:15
【问题描述】:

我希望我的选项列表以英国开头。

html:

<select  class="form-control" name="country" id="country-choice">
<option ng-repeat="x in ages | orderBy: COUNTRY==='United Kingdom of Great Britain and Northern Ireland'" value="">{{ x.COUNTRY }}</option>
 </select>

json:

{
         "COUNTRY":"United Kingdom of Great Britain and Northern Ireland",
         "SEX":"Male",
         "Value":"79"
      },

请不要担心 json 的接线,它工作正常。我只想让我的列表以英国开头并显示其他国家。使用过滤器英国隐藏所有其他国家,我不想要这个。我希望英国在顶部,然后是其余的......即阿富汗等,因为它将按字母顺序排列。

【问题讨论】:

  • 对数组进行预排序并将英国放在首位? orderBy 只需要属性名称来排序。
  • 天哪,你是对的,就这么简单!

标签: javascript json angularjs


【解决方案1】:

你可以看看这里:https://stackoverflow.com/a/12041694/2576531

编写一个自定义函数来为国家/地区赋值。所以你可以给英国一个额外的高价值。

$scope.myValueFunction = function(country){
  if(country == "United Kingdom of Great Britain and Northern Ireland"){
    return Number.MAX_VALUE;
  }

  return country;
};

在你的模板中你可以使用orderBy: myValueFunction

此示例期望 ng-repeat 遍历包含您所在国家/地区的数组。如果您的 ng-repeat 迭代您发布的 json 对象数组,那么您应该使用以下函数:

$scope.myValueFunction = function(yourEntity){
  if(yourEntity.COUNTRY == "United Kingdom of Great Britain and Northern Ireland"){
    return Number.MAX_VALUE;
  }

  return yourEntity.COUNTRY ;
};

Here is the working jsFiddle

【讨论】:

    【解决方案2】:

    您还可以创建自定义过滤器来实现此目的:

    /**
     * ukOnTop Filter
     * Puts the 'United Kingdom of Great Britain and Northern Ireland' string in ng-options or ng-repeat on top
     * @example
     *   ng-repeat="x in ages | ukOnTop"
     * @param  {Array|Object} array or hash
     * @return {Array}
     */
    app.filter('ukOnTop', function(orderByFilter) {
      return function (array) {
        if(!array) { return; }
        array = orderByFilter(array, 'COUNTRY'); // sort alphabetically
    
        // get UK 
        var ukObj = array.filter(function (obj) {
          return obj.COUNTRY === 'United Kingdom of Great Britain and Northern Ireland';
        })[0];
    
        // put it on top
        if(ukObj) {
          array.splice(array.indexOf(ukObj), 1);
          array.unshift(ukObj);
        }
        return array;
      };
    });
    

    working JSfiddle

    【讨论】:

    • 使用此解决方案而不是自定义值函数有什么好处?
    • 如果你想重用过滤器会更容易,否则你需要在你的所有控制器中定义自定义值函数;)
    • 对我来说很有意义 :) +1
    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    相关资源
    最近更新 更多