Josi Josi - 10 months ago 40
AngularJS Question

Cannot display default value in Angular JS Select control when coming from a diferent service than data in the list

I´ve been looking for other questions about Select using Angular but I think they all talk about populating hardcoded data into the select or maybe just from one service. In my case I want to populate data coming from one service, but choose the default option that has been retrieved from another service.

In this case, every Reservation contains a field with a Customer, so I want to display all customers names in the select (customers.shortName), but the default value comes from the reservation (reservation.customerName). Controller:

$scope.reservation ={id: $});
$scope.customers= CustomersFactory.query();


<select ng-model="reservation.customerName" ng-options="x.shortName for x in customers" required class="form-control" id="customerName" placeholder="customer name"><select/>

The data is populated correctly, but I can´t find a way of showing the default data (reservation.customerName). I have also made it work hardcoding the list of customers into the controller or setting for instance the first value of the list as default, but when calling 2 services it doesn´t work. I think it makes sense because I´m calling 2 asynchronous services, so maybe I should do something to refresh the select. Any ideas? Thanks!

Answer Source

Try this:

<select ng-model="reservation.customerName">
    <option ng-repeat="x in customers" value="{{x.shortName}}">{{x.shortName}}</option>