1

I have an Angular $resource something like this:

{
  _id: '1'
  items: [
    {_id: 'a'}, {_id: 'b'}, {_id: 'c'}
  ]
}

I'm trying to construct a form such that there is one checkbox for each element in the items array and in the act() function I can detect which elements of that array were selected with a checkbox.

The markup is something like:

<form ng-submit="act()">
  <input type="checkbox" ng-model="item._id" ng-repeat="item in items">
  <button type="submit">Submit</button>
</form>

However, I can't figure out how to access the array of item ids represented by the checked checkboxes inside the controller's act() function.

I've tried accessing the FormController in the scope but can't seem to get the values from there – only the validity state. I've tried binding the checkboxes to an array in the scope using ng-model but it's always empty in the act() function.

2 Answers 2

2

You can add a field called checked to each item on the fly, and in your controller, you can access $scope.items and filter out the checked items.

<input type="checkbox" ng-model="item.checked" ng-repeat="item in items">

$scope.act = function () {
    var checkedItems = [];
    angular.forEach($scope.items, function (item) {
        if (item.checked !== undefined && item.checked) checkedItems.push(item);
    });
    console.log(checkedItems)
}

Working Demo

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

Comments

1

You can store the values that are checked in an object where the key is the item's id. Then filter the object to only return the values that are true (checked).

Example: http://jsfiddle.net/TheSharpieOne/b3dkU/1/

Full controller:

function myCtrl($scope){
    $scope.selected = {};
    $scope.var = {
      _id: '1',
      items: [
        {_id: 'a'}, {_id: 'b'}, {_id: 'c'}
      ]
    };
    function isChecked(obj){
        var checked = [];
        for(var key in obj){
            if(obj[key])
                checked.push(key);
        }
        return checked;
    };
    $scope.act = function(){
        $scope.checked = isChecked($scope.selected);
    };
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.