Setting ngTrueValue and ngFalseValue to numbers

AlexFoxGill picture AlexFoxGill · Jan 17, 2014 · Viewed 67.5k times · Source

Update: question is obsolete for latest Angular version, see tsh's comment on this post


I have bound a checkbox to a value:

<input type="checkbox" ng-model="checkbox" ng-true-value="1" ng-false-value="0" />

The value of the checkbox is set to 1 in the controller:

function Controller($scope) {
    $scope.checkbox = 1
}

However, initially the checkbox does not appear checked. If I change the initial value of $scope.checkbox to "1", it does. (jsfiddle demo)

I have tried all kinds of variations:

ng-true-value="{{1}}"
ng-true-value="{{Number(1)}}"
ng-true-value="{{parseInt('1')}}"

None of them work. How can I make angular treat the arguments as a number?

Answer

Satpal picture Satpal · Jan 17, 2014

You can use ngChecked, If the expression is truthy, then special attribute "checked" will be set on the element

<input type="checkbox" 
    ng-model="checkbox" 
    ng-true-value="1" 
    ng-false-value="0" 
    ng-checked="checkbox == 1" />

And you can use $scope.$watch to convert it to number

$scope.$watch(function(){
    return $scope.checkbox;
}, function(){
    $scope.checkbox = Number($scope.checkbox);
    console.log($scope.checkbox, typeof $scope.checkbox);
},true);

DEMO