Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  147] [ 2]  / answers: 1 / hits: 26564  / 11 Years ago, wed, november 27, 2013, 12:00:00

Please note this example:



JSFiddle Sample





<div ng-controller=myCtrl>
var ng-model = {{myValue}} - {{myType}}

<input type=radio value=true
name=boolean ng-change=logIt() ng-model=myValue /> True
<input type=radio value=false
name=boolean ng-change=logIt() ng-model=myValue /> False

</div>
var myApp = angular.module('myApp',[]);

function myCtrl($scope)
{
$scope.myValue = true; //does not work
//$scope.myValue = 'true'; //it does work
$scope.myType =(typeof $scope.myValue);
$scope.logIt=function(){
$scope.myType =(typeof $scope.myValue);
}
}



As you can see initially typeof is of type boolean but after selecting a value it changes to string, and true is not equal to 'true'. Is there any way I can make angular preserve the original type.



At this point I am considering to write my own directive to control this behavior but it does not look right that angular changes the original type, am I correct?.


More From » angularjs

 Answers
15

Use ng-value and angular will handle converting back to boolean:



Here is the updated jsfiddle.



And obligatory code:



<div ng-controller=myCtrl>
<h1>Sample 1- Booleans</h1>

var ng-model = {{myValue}} - {{myType}}
<br />
<input type=radio ng-value=true name=boolean ng-change=logIt() ng-model=myValue /> True
<input type=radio ng-value=false name=boolean ng-change=logIt() ng-model=myValue /> False
</div>

[#74029] Tuesday, November 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;