0

I have a data service that says:

myApp.factory('locationsData', function ($resource) {


return $resource('/api/Location/:id', { id: '@id' }, { update: { method: 'PUT' } });});

I then use these locations to populate a dropdown in my view:

<select ng-model="locationId" ng-options="item.LocationId as item.LocationName for item  in locations"></select>

I want to set the init value of the dropdown in my controller with:

$scope.locationId = 8;

This doesn't work, i think because of the async nature of $resource -- it doesn't have the list yet so i can't set it.

I know $q is designed to address this, but not sure on how to create the promise, and set

$scope.locationId = 8;

after it is fulfilled

I've read the $q and $resource documentation, but i have yet to see a good code sample of how one would do a simple get like i'm doing, and then execute some function/action after the get promise is fulfilled.

Thanks.

user2375056
  • 55
  • 1
  • 5

1 Answers1

0

I believe somewhere in the controller you would be doing

$scope.locations=locationsData.query();

The query or get method can take argument for success and error functions. Something like

locationsData.query(function(data){
});

So you should set

$scope.locationId = 8;

inside the success function of the query.

Chandermani
  • 42,589
  • 12
  • 85
  • 88
  • So i don't need $q ? This seems to work. Except when the ng-model property is on an object e.g. `$scope.location.locationId`, when i try to access it in the controller, e.g. `$scope.location.locationId = 8;` it doesn't go. I can fix that by doing `$scope.location = [];` in the controller, but then when i submit my form, the location object is empty. I'm probably doing something stupid here. – user2375056 Jun 23 '13 at 15:19
  • You don't. Also $scope.location.locationId would work as long as your binding in html template is ng-model="location.locationId". – Chandermani Jun 24 '13 at 03:39