3

I want to populate a dropdown list with a few custom values using Angular.js ngOptions

Eg:-

<option value="' + info[x].CountryCode 
                 + '"   data-image="images/msdropdown/icons/blank.gif" 
        data-imagecss="flag ' + info[x].CountryCode 
                              + '" data-title="'
                              + info[x].CurrencyName + '" >' 
                              + info[x].CurrencyCode + '
</option>

Following is the data in JSON format :

[{
    "Id": 3,
    "CountryName": "Australia",
    "CountryCode": "au",
    "CurrencyCode": "AUD",
    "CurrencyName": "Australian Dollar",
    "CurrencyValue": 0.018,
    "PayPalCountryCode": 12,
    "PayPalCurrencyCode": 78,
    "IsActive": true
  },
  {
    "Id": 19,
    "CountryName": "Taiwan",
    "CountryCode": "tw",
    "CurrencyCode": "TWD",
    "CurrencyName": "New Taiwan Dollar",
    "CurrencyValue": 0.48,
    "PayPalCountryCode": 208,
    "PayPalCurrencyCode": 148,
    "IsActive": true
  },
  {
    "Id": 2,
    "CountryName": "United States",
    "CountryCode": "us",
    "CurrencyCode": "USD",
    "CurrencyName": "US Dollar",
    "CurrencyValue": 0.016,
    "PayPalCountryCode": 225,
    "PayPalCurrencyCode": 125,
    "IsActive": true
  }]

I am new to Angular, could someone show me how to do this using ngOptions ?

1
  • This is different one. This is based on custom attributes. But your suggested one is not support custom attributes. there is a huze difference Commented May 3, 2014 at 8:21

1 Answer 1

4

As per Angular ng-options documentations there are no custom attributes support. so use ng-repeat directive to achieve your select box

<select ng-model="countrySelected" ng-change="countryChange()">
  <option ng-repeat="country in countries" value="{{country.CountryCode}}" 
          data-image="images/msdropdown/icons/blank.gif" 
          data-imagecss="flag  {{country.CountryCode}}" 
          data-title="{{country.CurrencyName}}">{{country.CurrencyCode}}</option>
</select>

you get the selected value through ng-model. countrySelected stores your selected value.

in your controller

$scope.countryChange = function(){

// write your related code
}
Sign up to request clarification or add additional context in comments.

3 Comments

But i also want an onchange event on the select...Is that possible? What i mean is a function has to be called on changing the options.
use ng-change to call function on option change
The disadvantage of your approach is that if the option is supposed to represent a null value then the model is updated with an empty string instead of null value when the use selects that option.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.