Search code examples
angularjsangularjs-ng-repeathtml-selectangular-ngmodel

Using Angular.js with multiple html select fields, ng-repeat (and ng-model)


I'm trying to use angularjs with multiple html select fields and I want to store all the selected elements in an array.

May code would look like this:

<body ng-app="" ng-controller="myController">
{{selectedElements}}
<div ng-repeat="elem in selectedElements">
    <select 
        ng-model="elem.someThing"   <-- I do not want the someThing here
        ng-options="obj.name for obj in objects">
     </select>

    {{elem}}
</div>
<script>
    var myController = function ($scope) {
        $scope.selectedElements = [{},{}]

        $scope.objects = [
            {"id": "1234","name": "a"}, 
            {"id": "12345","name": "b"},
            {"id": "123456","name": "b"},
            {"id": "123458","name": "c"}
        ];
    };
</script>

You can also find a fiddle here: http://jsfiddle.net/dg76hetu/12/

The issue is, that I do not really want to use:

ng-model="elem.someThing"

because my selectedElements Array then includes "someThing" as a key. (see in fiddle) Intuitively I would want to do something like:

ng-model="elem"

However, this does not work and I am also aware that I should not bind to the model without the dot notation.

So my question is, how can I use angular to store all the selected objects from the multiple select fields inside the "selectedElements" Array? I feel like I am missing something basic, however I just can't get it to work.

Any help is highly appreciated.


Solution

  • You can link ng-model to actual value using $index and passing array[$index] in to ng-model directly.