如何在 AngularJS 中获取复选框的所有选定对象? [英] How can I get all the selected objects of Checkboxes in AngularJS?
问题描述
我想使用 AngularJS 获取复选框的所有选定对象.
下面是我的代码
我的 view.tpl.html
<td><input type="checkbox" ng-click="clickedItem(item.id)"ng-model="model.controller.object"{{item.name}}/></td>我的控制器
$scope.itemList = [{编号:1",名称:第一项"},{编号:2",标题:第二项"},{编号:3",标题:第三项"}];$scope.selection = [];$scope.clickedItem = function(itemId) {var idx = $scope.selection.indexOf(itemId);如果 (idx > -1) {$scope.selection.splice(idx, 1);}//是新选择的别的 {var obj = selectedItem(itemId);$scope.selection.push(obj);}};功能selectedItem(itemId){for (var i = 0; i < $scope.itemList.length; i++) {if ($scope.itemList[i].id === itemId) {返回 $scope.itemList[i];}}}
这里我将获取$scope.selection
中所有选中的项目.我怎样才能得到它ng-model
?
是否可以像 ng-model="model.controller.object = selection"
那样做,因为我需要将选定的 $scope.selection
分配给 <代码>model.controller.object
解决方案 如果我理解正确,您想创建一个复选框并将其动态绑定到列表中的一个项目,如果是这样,我将这样做这样做:
$scope.modelContainer=[];angular.forEach($scope.itemList,function(item){$scope.modelContainer.push({item:item,checked:false });});
HTML:
{{项目名称}}<input type="checkbox" ng-click="selected(item.id)" ng-model="modelContainer[$index].checked"/>
请参阅 plunk.每当您选中复选框时,都会在控制台中查看模型容器的变化.
I want to get all the selected objects of the checkboxes using AngularJS.
Below is my code
My view.tpl.html
<tr ng-repeat="item in itemList">
<td>
<input type="checkbox" ng-click="clickedItem(item.id)"
ng-model="model.controller.object"
{{item.name}} />
</td>
My Controller
$scope.itemList = [
{
id:"1",
name:"first item"
},
{
id:"2",
title:"second item"
},
{
id:"3",
title:"third item"
}
];
$scope.selection = [];
$scope.clickedItem = function(itemId) {
var idx = $scope.selection.indexOf(itemId);
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
var obj = selectedItem(itemId);
$scope.selection.push(obj);
}
};
function selectedItem(itemId) {
for (var i = 0; i < $scope.itemList.length; i++) {
if ($scope.itemList[i].id === itemId) {
return $scope.itemList[i];
}
}
}
Here I will get all the selected items in $scope.selection
. How can I get it to ng-model
?
Is it possible to do like ng-model="model.controller.object = selection"
since I need the selected $scope.selection
to be assigned to model.controller.object
解决方案 If I understand correctly you want to create a checkbox and dynamically bind it to an item(s) from a list, if so this is how I would go about doing it:
$scope.modelContainer=[];
angular.forEach($scope.itemList,function(item){
$scope.modelContainer.push({item:item,checked:false });
});
HTML:
<div ng-repeat="item in itemList">
{{item.name}}
<input type="checkbox" ng-click="selected(item.id)" ng-model="modelContainer[$index].checked" />
</div>
See plunk. See the model container change in the console whenever you check a checkbox.
这篇关于如何在 AngularJS 中获取复选框的所有选定对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文
登录
关闭
扫码关注1秒登录
发送“验证码”获取
|
15天全站免登陆