Reputation: 1069
I am stuck trying to pass a value from ng-repeat to my AngularJS controller. I don't feel like I know what anything is doing anymore. I keep trying different changes, but with no success.
My goal is to 1) display an array as options in a dropdown box. 2) Let the user select an option then 3) click a button that submits that choice to the Angular function.
I know the Angular function (I didn't include in this example) is working because I can pass a value to it statically and see the updates I expect. The problem is how do I capture the user selection in a variable that I can pass as a parameter to my $scope function named $scope.changeHost(newHost)
. Here is the AngularJS HTML I am having trouble with:
<form ng-submit="changeHost(newHost)">
<select type="text" class="form-control" ng-model="eveSingle.evePlayers">
<option ng-selected="{{eveSingle.evePlayers}}" value="{{eveSingle.evePlayers}}" ng-repeat="player in eveSingle.evePlayers">{{player}}</option>
</select>
<input class="btn submit-btn" type="submit" value="Change GM" />
</form>
Here is the (now abandoned) modified code that works as I intended:
<form ng-submit="changeHost(eveSingle.eveHost)">
<select type="text" class="form-control" ng-model="eveSingle.eveHost" ng-options="player for player in eveSingle.evePlayers">
<option type="text" value="{{eveSingle.evePlayers}}">{{player}}</option>
</select>
<input class="btn submit-btn" type="submit" value="Change GM" />
</form>
Here is a Final update because of a comment below. Once I changed to ng-options
I no longer needed the HTML options in my code. When I removed it this bit still worked fine.
<form ng-submit="changeHost(eveSingle.eveHost)">
<select class="form-control" ng-model="eveSingle.eveHost" ng-options="player for player in eveSingle.evePlayers">
</select>
<input class="btn submit-btn" type="submit" value="Change GM" />
</form>
Upvotes: 0
Views: 99
Reputation: 28219
The user selection is the value of the variable binded to the ng-model
. Therefore change ng-model="eveSingle.evePlayers"
to ng-model="eveSingle.selectedPlayer"
(adapt the name to your needs), and pass the selected player to changeHost
:
ng-submit="changeHost(eveSingle.selectedPlayer)"
Notice that you should remove ng-selected="{{eveSingle.evePlayers}}"
and type="text"
(this applies to input elements).
As a side note, be advised that you can (should) use the ng-options
syntax over the ng-repeat
-ed options. The first allows you to bind to the model other types than strings, plus it is more efficient as it doesn't create isolated scopes for each option. Would be something like that:
<select class="form-control" ng-model="eveSingle.selectedPlayer"
ng-options="player for player in eveSingle.evePlayers">
</select>
Upvotes: 1