Question

I have an angular select2 as follows:

<select ui-select2 id="clientID" name="clientID" ng-model="newTicket.clientstate" ng-required="true">
    <option ng-repeat="item in clients track by item.id" value="{{item.clientID}}|{{item.stateID}}" >{{item.displayName}}</option> 
</select>

in my controller, clients is set like this (calling a service that returns a $promise from a $resource):

TicketService.getClients().then(
    function(clients) {
        $scope.clients = clients;
    }
);

I also set the initial value of $scope.newTicket.clientstate in the controller. Because the call to the $resource is asynchronous, the setting of the initial value happens before the query resolves.

I'm trying to get the dropdown to populate an initial value ("DEMO|DEMO") after the API call completes. I think that the solution is one of 3 things: setting ng-init on the select, setting ng-selected on the ng-repeat, or doing something in the .then() that happens after the API returns the query. I can't seem to get the right syntax to work however, and I was hoping to get some advice on how to proceed.

My first effort to solve things (you can see that in the comments below) was to convert everything to an ng-options, but the ui-select2 library is incompatable with ng-op[tions, so I'm looking for another possibility.

Was it helpful?

Solution

I just ran into this same thing and a guy at work pointed me in the right direction.

It turns out you and I were both trying to over-complicate the solution. All you have to do is:

TicketService.getClients().then(
    function(clients) {
        $scope.clients = clients;
        // set the default value after the list comes back
        $scope.newTicket.clientstate = 'yourDefaultValue';  
    }
);

Then you should be good to go!

Just make sure that you have initialized $scope.newTicket before this, or you will get an error saying you can't access properties of an undefined object.

And I'm assuming that getClients() returns a $promise object? Otherwise you will need to do either:

TicketService.getClients(function(clients){...}))

or:

TicketService.getClients().$promise.then(function(clients){...}))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top