【发布时间】:2015-01-14 18:11:09
【问题描述】:
我想从复选框列表中保存所选项目的列表,该列表由 Angular 服务生成,如下所示。
不幸的是,我的“作业”对象只保留最后一个选中复选框的状态,而不是列表中所有选中复选框的 id 值。
谁能告诉我我做错了什么?
Plunker 与整个示例: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>
【问题讨论】:
-
我按照stackoverflow.com/questions/14514461/…的例子编写了这个代码
标签: javascript angularjs checkbox