单选按钮中的 ng-model 类型更改 [英] ng-model changes of type in radio button

查看:33
本文介绍了单选按钮中的 ng-model 类型更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意这个例子:

JSFiddle 示例

<预><代码><div ng-controller="myCtrl">var ng-model = {{myValue}} - {{myType}}<input type="radio" value="true"name="boolean" ng-change="logIt()" ng-model="myValue"/>真的<input type="radio" value="false"name="boolean" ng-change="logIt()" ng-model="myValue"/>错误的

var myApp = angular.module('myApp',[]);函数 myCtrl($scope){$scope.myValue = true;//不起作用//$scope.myValue = 'true';//它确实有效$scope.myType =(typeof $scope.myValue);$scope.logIt=function(){$scope.myType =(typeof $scope.myValue);}}

正如您所看到的,typeof 最初是布尔类型,但在选择一个值后它会更改为字符串,并且 true 不等于 'true'.有什么办法可以让 angular 保留原始类型.

此时我正在考虑编写自己的指令来控制这种行为,但 angular 改变原始类型看起来不太正确,我说得对吗?.

解决方案

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

这是更新的jsfiddle.

和强制性代码:

<h1>示例 1-布尔值</h1>var ng-model = {{myValue}} - {{myType}}<br/><input type="radio" ng-value="true" name="boolean" ng-change="logIt()" ng-model="myValue"/>真的<input type="radio" ng-value="false" name="boolean" ng-change="logIt()" ng-model="myValue"/>错误的

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

解决方案

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>

这篇关于单选按钮中的 ng-model 类型更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆