antonyboom antonyboom - 1 month ago 10
Javascript Question

different 'select all' checkboxes for different lists of checkboxes, angularjs

On my page I have a three list of checkboxes. Each list has an own checkbox "select all". I do not want to increase code with duplicating lines, that's why I'm using the same function with parameter to select certain list of checkboxes

$scope.selectAll = function(array) {
angular.forEach(array, function(item) {
item.Selected = $scope.model.selectedAll;
});
};


html

<input type="checkbox"
ng-model="model.selectedAll"
ng-change="selectAll(categories)" >


It gives me desirable result, I can select all checkboxes in certain array.
But here is the problem.
$scope.model.selectedAll
related to all lists and when I select all at the one list, checkbox "select all" is checked in all lists.

I clearly understand this problem, I just don't have any idea how to resolve it. I have been thinking about creating of 3 different variables for each list but I'm using function with parameter, where array is unknown, so I cannot associate certain variable with it and it won't be working.

Is there any way to resolve this problem without duplicating code for particular list of checkboxes?

thanks in advance.

here is my plunker

Answer

The way you've done this binds a set of non-related entities to the same model, which means that you've bound them very tightly. Obviously the goal is to keep them separated, so you'll need a different model, and there are a few ways to do that.

Using Entirely Unique Models

One way to do this is to just make your code a little more general and then a series of unique models associated with each checkbox, like so:

html

<input type="checkbox"
       ng-model="model1.selectedAll" 
       ng-change="selectAll(categories1, model1.selectedAll">

JS

$scope.selectAll = function(array, value) {
  angular.forEach(array, function(item) {
    item.Selected = value;
  });
};

Using a Base Model

Alternatively,if you don't want to keep track of multiple variables, you can encapsulate them into a single base. This method is useful if you have dynamically-created elements.

html

<input type="checkbox"
       ng-model="modelSet[key].selectedAll" 
       ng-change="selectAll(categories, key)">

JS

$scope.selectAll = function(array, key) {
  angular.forEach(array, function(item) {
    item.Selected = $scope.modelSet[key].selectedAll;
  });
};

Whatever you do, note that your selection function is getting more information from the view and less information from the $scope. You want to provide your utility function with as much context as possible so that it can reused more reliably.