vitalets / checklist-model

AngularJS directive for list of checkboxes
http://vitalets.github.io/checklist-model
MIT License
1.05k stars 206 forks source link

Cannot select all using a separate checkbox #134

Closed krojew closed 8 years ago

krojew commented 8 years ago

I'm trying to implement a "select/deselect all" feature using a separate checkbox with a typical ng-model:

<input type="checkbox" ng-model="selectAll" ng-change="toggleSelectAll()" />

<tr ng-repeat="message in messages">
    <td class="text-center">
        <input type="checkbox" checklist-model="selectedMessages" checklist-value="message.id" />
    </td>
</tr>

My toggleSelectAll function looks like this:

$scope.toggleSelectAll = function() {
        if ($scope.selectAll) {
            $scope.selectedMessages = $scope.messages.map(function(message) {
                return message.id;
            });
        } else {
            $scope.selectedMessages = [];
        }
    };

Unfortunately, it only works for the first time the select all checkbox is clicked. Further changes do change the checklist model, but the checkboxes themselves do not change their visual state. Basically, the checkboxes and the model become desynchronized.

beradrian commented 8 years ago

Could you please try and let me know if it's fine?

    $scope.toggleSelectAll = function() {
        if ($scope.selectAll) {
            $scope.selectedMessages.splice(0, $scope.selectedMessages.length);
            for (var i = 0, n = $scope.messages.length; i < n; i++) {
                  $scope.selectedMessages.push($scope.messages[i].id);
            }
        } else {
            $scope.selectedMessages.splice(0, $scope.selectedMessages.length);
        }
    };
krojew commented 8 years ago

Your solution seems to work - the messages are being selected/deselected.

beradrian commented 8 years ago

Great! Then I'll close the issue.

krojew commented 8 years ago

The question still remains - why setting an empty list didn't clear the selection? This seems to be the most obvious way to do it instead of using splice(), so people might stumble upon this behavior.

beradrian commented 8 years ago

I documented this in the README. I'll take a look to see how this can be improved.