ShaqCode
ShaqCode

Reputation: 381

Check box selection in table using AngularJS

I am trying to create a method that receives an Id from the table, when a checkbox has been checked, and should update the $scope.selected in the angular controller. And when the checkbox is uncheked, then it should remove it from the $scope.selected again.

So far it looks like this:

$scope.updateselection = function(id) {
   if ($scope.selected(sort_id) != id) { //what is the correct syntax here??
       $scope.selected.push({ sort_id: id });
   } else {
       $scope.selected.remove({ sort_id: id });
   }
};

Upvotes: 1

Views: 2094

Answers (1)

Artyom Pranovich
Artyom Pranovich

Reputation: 6962

For interaction with ckeckboxes in Angular I've recommend to use the following directive: http://vitalets.github.io/checklist-model/

If you don't want to use this directive, you can create watcher on your checkboxes table.

For example:

HTML:

<table>
    <tr>
        <td ng-repeat="item in items">
            <input type="checkbox" ng-model="item.value"> 
        </td>
    </tr>
<table>

JS:

 $scope.items = [
        {
            name: "name1",
            value: true
        },
        {
            name: "name2",
            value: false 
        }
    ];

    $scope.selectedItems = [];

    $scope.$watch('items', function(newValues){
        $scope.selectedItems.length = 0;
        angular.forEach(newValues, function(item) {
            if (item.value == true) {
                $scope.selectedItems.push(item.name);
            }
        });
        console.log($scope.selectedItems);
    }, true);

This way will allow you to always have the actual information about the selected checkbox.

I've created JSFiddle with working example for you.

Upvotes: 1

Related Questions