在单选按钮类型的NG-模式的变革 [英] ng-model changes of type in radio button

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

问题描述

请注意这个例子:

的jsfiddle样品



    <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类型,但选择它更改为字符串值后,和真实不等于真。有没有什么办法可以让角preserve原始类型。

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

推荐答案

使用 NG-值和角度将处理转换回布尔值:

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

下面是更新的jsfiddle

和强制性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-模式的变革的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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