4

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

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is not my case. Please read my question again. Especially last 2 lines
I did read your question, but I'm telling you to take a step back and reconsider what you want to do, since what you asked for doesn't make sense :)
Good answer. If you want each checkbox to have its own unique variable, then you actually need to make each variable. The method described in this answer is about as clean a way to do this as it can get.
This worked like a charm. Thanks for the answer. However, there is a bug: when unselect the checkbox after mistakenly selected, object is remaining as selected. How to fix this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.