View on GitHub

Angular-checkboxes

Bind a list of checkboxes to a unique ng-model array

Download this project as a .zip file Download this project as a tar.gz file

Welcome to Angular-checkboxes live Demo.

If you are used to manipulate HTML forms, you probably know that each checkbox is a separate variable (or maybe an ngModel with AngularJS).

Sometimes, it could be usefull to manipulate all these checkboxes as a unique array. msieurtoph.ngCheckboxes module lets you turn this list of checkboxes into a unique array and provides an API to control it, without creating new scopes.

When you check/uncheck the checkboxes, the array is updated

When you add/remove values to/from the array, checkbox states are updated.

Basic Usage

Use the mt-to directive on a parent tag, to define the destination array.
Then add the mt-checkbox to your checkboxes.

The value of the mt-checkbox attribute is the value that will be stored.
This value is parsed, so it can be a plain value or a reference in the local scope

If the value is a string, do not forget to wrap it with quotes: mt-checkbox="'my string'"!

Scope :

$scope.myValue: {{myValue}}
$scope.checkboxList: {{checkboxList}}
  

Customize the values to store

The stored values can be any type (even array or object) :

Scope :

$scope.values: {{values}}
$scope.checkboxList: {{checkboxList}}
  

Mix the destinations

The mt-checkbox directive looks for the closest mt-to directive to know where to store the value.

Then you can use several mt-to and store values in different destinations

Scope :

$scope.checkboxList: {{checkboxList}}
$scope.checkboxList2: {{checkboxList2}}
$scope.checkboxList3: {{checkboxList3}}
  

Using ngModels

If ng-model is used on the checkboxes. The mt-checkbox directive will take advantage of the ngModelControllers and bind them to the destination(s).

During the initialisation phase, the priority goes to the mt-to values. If they differ from the ngModel ones, ngModels are updated to reflect them.

In this example, ngModel of second line is 'true' but the checkboxList does not contain 'bar', so the ngModel is turned to 'false'.

On the opposite, checkboxList contains 'baz', so the third ngModel is turned to 'true'.

Scope :

$scope.foo: {{foo}}
$scope.bar: {{bar}}
$scope.baz: {{baz}}
$scope.checkboxList: {{checkboxList}}
  

Advanced Usage

mt-checkbox directive publishes a controller. It provides:

In this example, we add a custom directive to the first checkbox. This directive uses this controller to modify the initial behavior

Scope :

$scope.checkboxList: {{checkboxList}}