Issue
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.
Solution
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)
}
Answered By - zs2020
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.