Search code examples
angularjsng-optionsngresource

Cannot bind ngResource to ngOptions


I have a select element, and I want it populated with the result of a call to a resource via ngResource.

 <select chosen="" 
         required 
         data-ng-model="coolStuffSelected" 
         data-ng-options="stuff for stuff in coolStuff" 
         class="chosen-select input-md"></select>

In my Controller I have

CoolStuffResource.query(function(result){
  $scope.coolStuff = result;
  console.log(JSON.stringify($scope.coolStuff));
  // prints ["foo","bar","gaz","waka"]
});

I see the result logged, but the select is empty. What am I doing wrong?

Update: I tried this albeit hacky workaround, which is to access the ng-model :

MyCoolService.query(function(result){
  $scope.coolStuff = result;
  $scope.coolStuffSelected = null;
});

This works in Chrome, but does not work in Safari. Simply hardcoding the values works fine in both browsers:

$scope.coolStuff = ["foo", "bar", "gaz", "waka"]; 

Solution

  • Here's a working JsFiddle from your other question, demonstrating the returned data from there.

    <select ng-model="selected" ng-options="d for d in data"></select>  
    

    JS:

    function MyCtrl($scope) {
        MyCoolResource.query(function(result){
           $scope.data = result;
        });
    }