How can I get all selected checkbox objects in AngularJS?

I want to get all selected checkbox objects 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 ng-model?

Is it possible to do this like ng-model="model.controller.object = selection"since I need to choose $scope.selectionformodel.controller.object

+4
source share
1 answer

If I understand correctly, you want to create a checkbox and dynamically bind it to an element from the list, if so, I would do this:

$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. . , .

+7

Source: https://habr.com/ru/post/1524136/


All Articles