I'd like to save a list of selected items from a checkbox list, generated with an angular service as follows.
Unfortunately, my "job" object only persists the state of the last selected checkbox, instead of the id values of all of the selected checkboxes in the list.
Could anyone tell me what am I doing wrong please?
Plunker with the entire example: http://plnkr.co/edit/znLy9EqUMZN6kRzNnl07?p=preview
<script type="text/javascript">
var app = angular.module('helloWorldApp', []);
app.service('HelloWorldService', function() {
var model = this;
var people = [{
"id": 0,
"firstName": "John",
"lastName": "Doe",
"expertise": "Programmer",
"checked": false
}, {
"id": 1,
"firstName": "Mary",
"lastName": "Jane",
"expertise": "Manager",
"checked": false
}];
model.getPeople = function() {
return people;
};
});
app.controller('HelloWorldController', ['$scope', 'HelloWorldService',
function($scope, HelloWorldService) {
var helloWorld = this;
// why this does not work?
// helloWorld.people = function() { return HelloWorldService.getPeople(); };
// why this one works?
helloWorld.people = HelloWorldService.getPeople();
$scope.selectedPeople = [];
helloWorld.selectedPeople = [];
$scope.createNewJob = function() {
console.log("Object: " + JSON.stringify($scope.job));
};
$scope.addPerson = function(id) {
// how can I keep a list of selected people in my ng-model object?
//helloWorld.selectedPeople.push(id + " selected");
$scope.selectedPeople.push(id + " selected");
helloWorld.selectedPeople = $scope.selectedPeople;
console.log($scope.selectedPeople);
}
}
]);
<tbody ng-controller="HelloWorldController as helloWorld">
<tr ng-repeat="person in helloWorld.people">
<td>
<input type="checkbox" name="peopleList[]" ng-model="job.selectedPeople" ng-click="addPerson(person.id)" value="{{person.id}}" />
<label>{{person.firstName}} {{person.lastName}}</label>
</td>
<td>
{{person.expertise}}
</td>
</tr>
</tbody>