Robert
Robert

Reputation: 4406

Why isn't the select tag populating my ng-options?

I have the array back from the server and the local $scope.customers is populated (I have verified this in the debugger); however, I cannot seem to populate my select tag with the array:

Angular Controller:

surchargeIndex.controller('SurchargeIndexController', [ "$scope", "customerService", "templateService",
    function ($scope, customerService, templateService) {
    customerService.getTest().then(function (customers) { $scope.customers = customers; });
    //templateService.getTemplates.then(function (templates) { $scope.getTemplates = templates; });
}]);

cshtml:

<div class="dropdown">
    <select ng-model="customerKey" ng-options="customer.Key as customer.Value for customer in customers"></select>
    <button id="getTemplates" class="btn btn-primary" ng-click="getTemplates(customerKey)">Get Templates</button>
</div>

When I inspect the select element there is nothing there but a single:

 <option value="?" selected="selected"></option>

JSON string:

[
    {
    Key: 500,
    Value: "Test Customer 1"
    },
    {
    Key: 11304,
    Value: "test Customer 2"
    },
    {
    Key: 11345,
    Value: "Test Customer 3"
    },
]

service:

surchargeIndex.service('customerService', [
    '$http', function ($http) {
        this.getTest = function () {
           return $http({
                    method: "GET",
                    url: "api/Customer/GetTest",
                })
                .success(function(data) {
                    return data;
                });
        };
    }
]);

I tried using ng-reepat on an option tag (I realize this is not the preferred way) and I get 15 (the number of items in the array) blank options.

What am I missing?

Upvotes: 0

Views: 51

Answers (1)

tasseKATT
tasseKATT

Reputation: 38490

The successCallback passed to then will receive a single argument in form of an object representing the response.

You want to use the data property:

customerService.getTest().then(function(result) {
  $scope.customers = result.data;
});

Alternatively you can use the success method instead. The callback passed to this receives four arguments:

success(function(data, status, headers, config) {

Example:

customerService.getTest().success(function(data) {
  $scope.customers = data;
});

Upvotes: 2

Related Questions