Christian Acosta
Christian Acosta

Reputation: 23

AngularJS populate ng-options with object

How would I go about populating a select if I was using ng-options?

So I have something like,

<select ng-model="option.model"
ng-options="option as (option.firstVal + ' ' + option.secondVal) 
  for option in options>
<option value="">default</option>

The value in each option is an entire object and the ng-option is going through a collection of objects.

I need the value to be the entire object to be the value so I can't use ng-repeat. When I try to assign the model to the object itself,

$scope.option.model = option; //option is made elsewhere

It doesn't work. It'll populate the field with the default option.

[Edit 1] In this example, the dropdown should be selected to John Rambo, but instead it goes to the default

jsfiddle.net/brzxn8yt/1

Upvotes: 1

Views: 373

Answers (1)

Naren Murali
Naren Murali

Reputation: 56054

you just need to use the track by property of ng-options. in the below example I track the object by the ID property.

Note: Please use a unique property in the object (E.g: id would be perfect since there are no duplicates, but actor property has duplicates and will throw and error).

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
    $scope.people = [
        { id: 1, first: 'John', last: 'Rambo', actor: 'Silvester' },
        { id: 2, first: 'Rocky', last: 'Balboa', actor: 'Silvester' },
        { id: 3, first: 'John', last: 'Kimble', actor: 'Arnold' },
        { id: 4, first: 'Ben', last: 'Richards', actor: 'Arnold' }
    ];
    
    $scope.selectedPerson = { id: 1, first: 'John', last: 'Rambo', actor: 'Silvester' }; // a person object
    
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
    <fieldset ng-controller="FirstCtrl">
        <select 
            ng-options="item as item.first + ' ' + item.last for item in people track by item.id"
            ng-model="selectedPerson">
              <option value="">Default</option>
            </select>
        {{ selectedPerson }}
    </fieldset>
</div>

Reference:

ng-options

Upvotes: 1

Related Questions