7

I need to use a country dropdown in my angular-breeze app, and I tried with the following: https://github.com/banafederico/angularjs-country-select

The problem here is that it doesn't have a country/code pair, just the long name of the country, which I don't want to save to the DB. Is there any other angular directive/service I can use to populate a dropdown with countries? I've done a bit of digging, but I didn't find any ready-to-use country select option for angular.

devC
  • 1,384
  • 5
  • 32
  • 56
  • I'd suggest creating your own. You can even fork that directory, and augment it. – Brian Noah Feb 09 '15 at 07:01
  • I was wondering, it seems a very common functionality and perhaps there's something already out there without me reinventing the wheel :) – devC Feb 09 '15 at 07:07
  • I generally don't like using other people's code. It often introduces more problems. That being said, there might be another one, but if there isn't build on top of the existing one. – Brian Noah Feb 09 '15 at 07:11
  • @CHAT_2013 how is a dropdown showing countries different from any other dropdown? Angular has `select`, `ng-model` and `ng-options` to create dropdowns. You don't need anything else. – JB Nizet Feb 09 '15 at 07:12
  • @JB Nizet: I was looking for an implementation that comes with the countrylist as well, without me having to define the country list separately as suggested in the below answer. – devC Feb 09 '15 at 07:56

1 Answers1

16

You can use ng-repeat or ng-options directive and create country dropdown. By this way, you have a full control. You can create as Directive if this element used in many places if needed.

Demo: http://plnkr.co/edit/2y9Jcektl8g2L0VoNQyp?p=preview

Using ng-option directive

<select ng-model="country" ng-options="country.name for country in countries track by country.code">
  <option value="">-- Select a Country --</option>
  </select>

Using ng-repeat directive:

<select ng-model="country">
    <option value="">-- Select a Country --</option>
    <option ng-repeat="country in countries" value="{{country.code}}">{{country.name}}</option>
</select>

Countries Scope in your controller:

    $scope.countries = [ 
        {name: 'Afghanistan', code: 'AF'},
        {name: 'Åland Islands', code: 'AX'},
        {name: 'Albania', code: 'AL'},
        {name: 'Algeria', code: 'DZ'},
        {name: 'American Samoa', code: 'AS'}
    ];
Asik
  • 7,967
  • 4
  • 28
  • 34
  • 1
    @CHAT_2013 This is why duplicating functionality is ok. It's basically a list that you have control over. and you do a simple loop. You can wrap it with a directive if you want. – Brian Noah Feb 09 '15 at 07:34
  • Fine, but you still have to generate the list of countries which is basically the main reason you would want such plugin. – Mark Odey Aug 07 '21 at 22:06