Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting ngTrueValue and ngFalseValue to numbers

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?

like image 764
Alex Avatar asked Jan 17 '14 17:01

Alex


1 Answers

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

like image 76
Satpal Avatar answered Sep 27 '22 23:09

Satpal