Javascript 按角度排序按特定属性排序

Javascript 按角度排序按特定属性排序,javascript,json,angularjs,Javascript,Json,Angularjs,我希望我的选择列表从英国开始 html: 请不要担心json的接线,它工作正常。我只想让我的名单从英国开始,并显示其他国家。使用过滤器英国隐藏所有其他国家,我不希望这样。我希望英国排在首位,然后是其他国家,如阿富汗等,因为它将按字母顺序排列 你可以看看这里: 编写一个自定义函数,为国家/地区指定一个值。所以你可以给英国一个超高的价值 $scope.myValueFunction = function(country){ if(country == "United Kingdom of Gre

我希望我的选择列表从英国开始

html:


请不要担心json的接线,它工作正常。我只想让我的名单从英国开始,并显示其他国家。使用过滤器英国隐藏所有其他国家,我不希望这样。我希望英国排在首位,然后是其他国家,如阿富汗等,因为它将按字母顺序排列

你可以看看这里:

编写一个自定义函数,为国家/地区指定一个值。所以你可以给英国一个超高的价值

$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 ;
};

您还可以创建一个自定义过滤器来实现这一点:

/**
 * 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;
  };
});

对阵列进行预排序,并将UK放在最前面?orderBy只需使用属性名进行排序。哦,天哪,你说得对,就这么简单!使用此解决方案而不是自定义值函数有什么好处?如果要重用筛选器,则更容易,否则需要在所有控制器中定义自定义值函数;)对我来说有意义:)+1
$scope.myValueFunction = function(yourEntity){
  if(yourEntity.COUNTRY == "United Kingdom of Great Britain and Northern Ireland"){
    return Number.MAX_VALUE;
  }

  return yourEntity.COUNTRY ;
};
/**
 * 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;
  };
});