Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all the selected objects of Checkboxes in AngularJS?

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

like image 476
Rajaa Avatar asked Feb 13 '23 23:02

Rajaa


1 Answers

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.

like image 59
Mohammad Sepahvand Avatar answered Apr 09 '23 22:04

Mohammad Sepahvand