Search code examples
angularjshtml-selectangular-ngmodelng-options

Angular - Select and ngOptions - Define key for value added to model


I have the following:

<select class="input-lg form-control" ng-model="selections[$index]" name="potsel" ng-options="selection.sel._id as selection.sel.name for selection in pot.selections" required ng-disabled="clicked">

I have 4 dropdowns being created, and this returns to me a $scope as follows (on submit):

$scope.selections = ["id1", "id2", "id3", "id4"]

Ideally, I'd like it look like this:

$scope.selections = [{"dropdown1":"id1"},{"dropdown2":"id2"},{"dropdown3":"id3"},{"dropdown4":"id4"}]

Note that "dropdown#" can be retrieved in the html by using "pot._id".

Been a while looking at this, and I can't see anywhere in ngOptions to define this. Any help please?

Thank you.


Solution

  • while you can do this directly in html, you can surely do this in js

          ng-change="selectionObj[$index] = {} ; selectionObj[$index][pot._id] = selections[$index]"
    

    or you can create a function, which will do above ng-change=addObject($index, pot._id, selections[$index])

         $scope.addObject = function(index, key, value) {
             $scope.selectionObj[$index] = { key : value   };   
         }
    

    EDIT

    sorry, replace $index with index.

             var obj = {}; 
             obj[key] = value; 
             $scope.selectionObj[index] = obj;
             console.log(key, value);