AlanObject
AlanObject

Reputation: 9943

Using AngularJS select element to set a variable to an object instead of a string

The following code works. My question is whether this is the right way to do it.

The variable devices is an array of objects and when the user selects one the variable selDev gets set to one of those objects. If I make selDev the model via the ng-model attribute then it gets a string, not the original model.

    <p>
        <label>Device Id:</label>
        <select ng-model="selDevIndex"
            ng-change="selDev = devices[selDevIndex]">
            <option value="">(no device)</option>
            <option ng-repeat="device in devices "
                    value="{{$index}}">
                {{device.id}}: {{device.type}} {{device.mfr}}
                {{device.serial}}
            </option>
        </select>
    </p>

I find this a little clumsy due to the inclusion of the $index reference. Also this technique would not work if devices was an object an not an array. Is there a better way?

Upvotes: 0

Views: 48

Answers (1)

The.Bear
The.Bear

Reputation: 5855

You can use ng-options

HTML:

  <select ng-model="selectedModel" 
          ng-options="device as device.text for device in devices track by device.id">
  </select>

CONTROLLER:

$scope.selectedModel;
$scope.devices = [{
   id: 1,
   text: "Device1"
}, {
   id: 2,
   text: "Device2"
}];

Check this jsFiddle
If you have to loop over an object instead of an array, check this post

Upvotes: 1

Related Questions