From 416b4858de7961e16f223ae833fc788c8c67e926 Mon Sep 17 00:00:00 2001 From: Caleb Kniffen Date: Mon, 8 Jun 2015 18:48:17 -0500 Subject: [PATCH] Required type validation only worked for the last checkbox. Fixes #26 --- src/types/multiCheckbox.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/types/multiCheckbox.js b/src/types/multiCheckbox.js index c0c5126..bda2716 100644 --- a/src/types/multiCheckbox.js +++ b/src/types/multiCheckbox.js @@ -17,6 +17,14 @@ export default ngModule => { valueProp: c.string.optional }) }, + defaultOptions: { + ngModelAttrs:{ + required: { + attribute: '', + bound: '' + } + } + }, apiCheckInstance: c, controller: /* @ngInject */ function($scope) { const to = $scope.to; @@ -35,6 +43,14 @@ export default ngModule => { }); } + function checkValidity(expressionValue){ + var 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, (checkbox, index) => { @@ -42,8 +58,27 @@ export default ngModule => { $scope.model[opts.key].push(to.options[index][to.valueProp || 'value']); } }); + + // Must make sure we mark as touched because only the last checkbox due to a bug in angular. + $scope.fc.$setTouched(); + checkValidity(true); + } + + if(opts.expressionProperties && opts.expressionProperties.required){ + $scope.$watch($scope.options.expressionProperties.required, function(newValue){ + checkValidity(newValue); + }); + } + + if($scope.to.required){ + var unwatchFormControl = $scope.$watch('fc', function(newValue){ + if(!newValue){ return; } + checkValidity(true); + unwatchFormControl; + }); } } }); } + };