0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.