Skip to content

Instantly share code, notes, and snippets.

@icfantv
Created December 11, 2015 00:10
Show Gist options
  • Save icfantv/18042d5fc22056343c29 to your computer and use it in GitHub Desktop.
Save icfantv/18042d5fc22056343c29 to your computer and use it in GitHub Desktop.
Multi Checkbox Example
module.controller('FormlyMultiCheckboxController', ['$scope', FormlyMultiCheckboxController]);
function FormlyMultiCheckboxController($scope) {
var to = $scope.to;
var opts = $scope.options;
$scope.multiCheckbox = {
checked: [],
change: setModel,
selectAll: false,
toggleSelectAll: toggleSelectAll
};
// initialize the checkboxes check property
$scope.$watch('model', function modelWatcher(newModelValue) {
var modelValue, valueProp;
if (Object.keys(newModelValue).length) {
modelValue = newModelValue[opts.key];
$scope.$watch('to.options', function optionsWatcher(newOptionsValues) {
if (newOptionsValues && Array.isArray(newOptionsValues) && Array.isArray(modelValue)) {
valueProp = to.valueProp || 'value';
for (var index = 0; index < newOptionsValues.length; index++) {
$scope.multiCheckbox.checked[index] = modelValue.indexOf(newOptionsValues[index][valueProp]) !== -1;
}
}
});
}
}, true);
function checkValidity(expressionValue) {
var valid;
if ($scope.to.required) {
valid = angular.isArray($scope.model[opts.key]) &&
$scope.model[opts.key].length > 0 &&
expressionValue;
$scope.fc.$setValidity('required', valid);
}
}
function setModel() {
$scope.model[opts.key] = [];
angular.forEach($scope.multiCheckbox.checked, function(checkbox, index) {
if (checkbox) {
$scope.model[opts.key].push(to.options[index][to.valueProp || 'value']);
}
});
// set the select all checkbox state as appropriate
$scope.multiCheckbox.selectAll = ($scope.model[opts.key].length === to.options.length);
// Must make sure we mark as touched because only the last checkbox due to a bug in angular.
$scope.fc[0].$setTouched();
checkValidity(true);
}
<div class="radio-group">
<div class="checkbox" ng-if="::to.showSelectOptions" style="border-bottom: 1px solid #777;">
<label>
<input type="checkbox"
id="{{ ::id }}"
ng-model="multiCheckbox.selectAll"
ng-change="multiCheckbox.toggleSelectAll()"/>
Select All</label>
</div>
<div ng-repeat="(key, option) in to.options" class="checkbox">
<label ng-class="to.data.labelFlags[$index] ? to.labelClass : ''">
<input type="checkbox"
id="{{ id + '_'+ $index }}"
ng-model="multiCheckbox.checked[$index]"
ng-change="multiCheckbox.change()"/>
{{ option[to.labelProp || 'name'] }}
</label>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment