0

I want my option list to start with United kingdom.

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"
      },

Please don't worry about the wiring up of the json, it is working fine. I just want my list to start with United Kingdom and show the other countries. Using filter United kingdom hides all the other countries and I do not want this. I want UK at the top, then the rest..ie Afganistan etc as it will be alphabetical.

artworkjpm
  • 1,255
  • 2
  • 19
  • 40

2 Answers2

1

You may have a look over here: https://stackoverflow.com/a/12041694/2576531

Write a custom function to give countries a value. So you could give United Kingdom an extra high value.

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

  return country;
};

in your template you can use orderBy: myValueFunction

This example expects ng-repeat to iterate over an array containing your countries. If your ng-repeat iterates over an array of the json-objects you posted then you should use the following function:

$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

Community
  • 1
  • 1
Yannic Bürgmann
  • 6,301
  • 5
  • 43
  • 77
1

You could also create an custom filter to achieve this:

/**
 * 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

Betty St
  • 2,741
  • 21
  • 33