如何在AngularJS中获取Checkbox的所有选定对象?
发布时间:2020-12-17 07:59:01 所属栏目:安全 来源:网络整理
导读:我想使用AngularJS获取复选框的所有选定对象. 以下是我的代码 我的view.tpl.html tr ng-repeat="item in itemList"tdinput type="checkbox" ng-click="clickedItem(item.id)" ng-model="model.controller.object" {{item.name}} //td 我的控制器 $scope.item
我想使用AngularJS获取复选框的所有选定对象.
以下是我的代码 我的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> 我的控制器 $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]; } } } 在这里,我将获得$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: <div ng-repeat="item in itemList"> {{item.name}} <input type="checkbox" ng-click="selected(item.id)" ng-model="modelContainer[$index].checked" /> </div> 请参阅plunk.每当您选中复选框时,请在控制台中查看模型容器更改. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |