Reputation: 4537
My goal is to have a set of checkboxes where users will make selections and when they hit the submit button, I'll print to the console what they chose.
My problem is that I can't seem to fetch the data from the checkbox group in my Javascript. I attempted to create a minimal reproducible example, but I can't even get the ng-repeat
working on jsfiddle :-S jsfiddle
I want to use ng-repeat
to create a bunch of checkboxes
<ul>
<li ng-repeat="game in games">
<input type="checkbox" ng-model="answers.games" value="{{game.game_id}}">{{game.game}}
</li>
</ul>
where on the javascript side I have something like
(function() {
var app = angular.module('myApp', []);
app.controller('playController', function($scope, $rootScope, $http){
getWeeks();
$scope.games = [
{game_id: 1, game: "Game 1"},
{game_id: 2, game: "Game 2"},
{game_id: 3, game: "Game 3"}
]
$scope.score_submission = function(){
console.log($scope.answers)
}
})
})();
But, the checkboxes don't bind to $scope.answers
the way I thought they would, instead, $scope.answers
remains undefined. What I'd like to get back is an array of the game_id
values that were checked.
Upvotes: 2
Views: 140
Reputation: 48968
Another approach is:
<ul>
<li ng-repeat="game in games">
<input type="checkbox" ng-model="selected[game.id]"> {{game.game}}
</li>
</ul>
$scope.selected = {};
Upvotes: 2
Reputation: 8713
The simplest approach might be...
<ul>
<li ng-repeat="game in games">
<input type="checkbox" ng-model="game.isSelected"> {{game.game}}
</li>
</ul>
In your controller:
$scope.score_submission = function(){
$scope.answers = [];
for(var i=0; i < $scope.games.length) {
if($scope.games[i].isSelected) $scope.answers.push($scope.games[i].game_id);
}
}
The only small downside of this solution is that you manipulate $scope.games - but I don't see a big disadvantage here as long as the lists are not too big.
Upvotes: 1