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 ?

Monodeep
  • 1,392
  • 1
  • 17
  • 39
  • This is different one. This is based on custom attributes. But your suggested one is not support custom attributes. there is a huze difference – chandu May 03 '14 at 08:21

1 Answers1

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
}
chandu
  • 2,276
  • 3
  • 20
  • 35
  • 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. – Monodeep Apr 27 '14 at 12:25
  • 1
    use ng-change to call function on option change – chandu Apr 27 '14 at 12:26
  • 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. – supertonsky May 12 '16 at 04:18