ng-model单选按钮中的类型更改

时间:2013-11-27 17:12:55

标签: javascript angularjs angularjs-directive radio

请注意这个例子:

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);
        }
    }

正如您所看到的,最初typeof的类型为boolean,但在选择一个值后,它会更改为string,而true不等于'true'。有什么方法可以让角度保留原始类型。

此时我正在考虑编写自己的指令来控制这种行为,但是看起来角度改变原始类型并不正确,我是否正确?。

1 个答案:

答案 0 :(得分:17)

使用ng-value和angular将处理转换回布尔值:

这是updated jsfiddle

强制性代码:

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