Skip to content

Commit 0a2df36

Browse files
committed
Suggested approach for supporting numerical true/false values in checkbox inputs.
1 parent 711a493 commit 0a2df36

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

src/ng/directive/input.js

+9-5
Original file line numberDiff line numberDiff line change
@@ -641,11 +641,8 @@ function radioInputType(scope, element, attr, ctrl) {
641641
}
642642

643643
function checkboxInputType(scope, element, attr, ctrl) {
644-
var trueValue = attr.ngTrueValue,
645-
falseValue = attr.ngFalseValue;
646-
647-
if (!isString(trueValue)) trueValue = true;
648-
if (!isString(falseValue)) falseValue = false;
644+
var trueValue = typedValue(attr.ngTrueValue, true),
645+
falseValue = typedValue(attr.ngFalseValue, false);
649646

650647
element.on('click', function() {
651648
scope.$apply(function() {
@@ -666,6 +663,13 @@ function checkboxInputType(scope, element, attr, ctrl) {
666663
});
667664
}
668665

666+
function typedValue(val, defaultVal) {
667+
return isString(val)
668+
? !isNaN(parseFloat(val)) && isFinite(val)
669+
? parseFloat(val)
670+
: val
671+
: defaultVal;
672+
}
669673

670674
/**
671675
* @ngdoc directive

test/ng/directive/inputSpec.js

+26-1
Original file line numberDiff line numberDiff line change
@@ -876,7 +876,7 @@ describe('input', function() {
876876
});
877877

878878

879-
it('should allow custom enumeration', function() {
879+
it('should allow custom string enumeration', function() {
880880
compileInput('<input type="checkbox" ng-model="name" ng-true-value="y" ' +
881881
'ng-false-value="n">');
882882

@@ -902,6 +902,31 @@ describe('input', function() {
902902
expect(scope.name).toEqual('n');
903903
});
904904

905+
it('should allow custom numerical enumeration', function() {
906+
compileInput('<input type="checkbox" ng-model="name" ng-true-value="1" ' +
907+
'ng-false-value="0">');
908+
909+
scope.$apply(function() {
910+
scope.name = 1;
911+
});
912+
expect(inputElm[0].checked).toBe(true);
913+
914+
scope.$apply(function() {
915+
scope.name = 0;
916+
});
917+
expect(inputElm[0].checked).toBe(false);
918+
919+
scope.$apply(function() {
920+
scope.name = 'something else';
921+
});
922+
expect(inputElm[0].checked).toBe(false);
923+
924+
browserTrigger(inputElm, 'click');
925+
expect(scope.name).toEqual(1);
926+
927+
browserTrigger(inputElm, 'click');
928+
expect(scope.name).toEqual(0);
929+
});
905930

906931
it('should be required if false', function() {
907932
compileInput('<input type="checkbox" ng:model="value" required />');

0 commit comments

Comments
 (0)