最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ng-model changes of type in radio button - Stack Overflow

programmeradmin2浏览0评论

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?.

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?.

Share Improve this question edited Jul 1, 2022 at 20:12 Jonas 129k101 gold badges326 silver badges405 bronze badges asked Nov 27, 2013 at 17:12 DalorzoDalorzo 20k7 gold badges57 silver badges102 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

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>
发布评论

评论列表(0)

  1. 暂无评论