2
votes

I have been trying to work with an object I am retrieving through an $http call and using to populate drop-down boxes.

My object looks like this:

{1: Item1
↵L", 2: "Item2
↵", 3: "Item3
↵"}

In my controller:

$scope.data = {};
$http.get(baseUrl + "/Lookup/Get?param=Ref_myModel").success(function (result) {

    $scope.data.myModel = result

})
.error(function (error) {
    $scope.data.error = error;
});

Finally in HTML:

 <select class="form-control" id="MonStatus" ng-model="data.myModel" ng-options="key as value for (key , value) in data.myModel"></select>

The select drop-down is populated with values from the model with no issue but as soon as the user selects a value, the value is replaced by the key. I have been reading through the documentation trying to understand ng-options however I am having some issues since all of the examples are using objects with proper key, value formats while I have a key and text.

1

1 Answers

3
votes

You're using $scope.data.myModel as your model and the source element for your options. These should be separate:

$scope.data = {};
$scope.data.myModel = '';
$http.get(baseUrl + "/Lookup/Get?param=Ref_myModel").success(function (result) {

    $scope.data.options = result

})
.error(function (error) {
    $scope.data.error = error;
});

Then in your view:

<select class="form-control" id="MonStatus"
    ng-model="data.myModel" 
    ng-options="key as value for  (key , value) in data.options"></select>

This will bind the selection to myModel and let the options remain what they were...

Some extra advice:

Also, don't do $http calls in your controllers, place them in a service. Always avoid logic as much as possible in your controllers and let services/factories take care of the heavy lifting. Also, it's a pretty good idea to place data- before ng-* attributes.