eldix_ eldix_ - 1 year ago 86
AngularJS Question

Using ng-options with JSON data

I'm still trying to find my way with AngularJS. I have a JavaScript code that uses URL to return JSON data as an array. I need help with populating the same data in select using ng-options.

data to populate on the select

Answer Source

This isn't how you ask for help, but nevermind. Given a JSON object like this

var JsonArray = [{
    id: 1, 
    name: 'Jane',
    address: 'Jane\'s house'
}, {
    id: 2, 
    name: 'Jill',
    address: 'Jill\'s house'
}, {
    id: 3, 
    name: 'John',
    address: 'John\'s house'
}, {
    id: 4, 
    name: 'Jack',
    address: 'Jack\'s house'

When you want to use ng-select with ng-options, you need to specify 3 required fields :

  • your table

  • the name that every object will take (like a for ... each loop)

  • The property you want to see in your options

You also can specify a track by property to give your options a given value.

<select ng-model="mySelect" ng-options="object.name for object in JsonArray track by object.id"></select>

Now, use the last piece of code, and inspect it in a brwoser. You will understand everything.

For reference :

<select ng-model="mySelect" ng-options="[object].[chosenProperty] for [object] in [yourArray] track by [object].[property]"></select>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download