将ngTrueValue和ngFalseValue设置为数字 [英] Setting ngTrueValue and ngFalseValue to numbers

查看:234
本文介绍了将ngTrueValue和ngFalseValue设置为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将一个复选框绑定到一个值:

I have bound a checkbox to a value:

<input type="checkbox" ng-model="checkbox" ng-true-value="1" ng-false-value="0" />

控制器中的复选框值设置为1:

The value of the checkbox is set to 1 in the controller:

function Controller($scope) {
    $scope.checkbox = 1
}

但是,最初复选框未显示选中状态。如果我将 $ scope.checkbox 的初始值更改为1,它会。 ( jsfiddle demo

However, initially the checkbox does not appear checked. If I change the initial value of $scope.checkbox to "1", it does. (jsfiddle demo)

我尝试过各种变体:

ng-true-value="{{1}}"
ng-true-value="{{Number(1)}}"
ng-true-value="{{parseInt('1')}}"


b $ b

它们都不工作。

None of them work. How can I make angular treat the arguments as a number?

推荐答案

您可以使用 ngChecked 如果表达式是真实的,那么将在元素上设置特殊属性checked。

You can use ngChecked, If the expression is truthy, then special attribute "checked" will be set on the element

<input type="checkbox" 
    ng-model="checkbox" 
    ng-true-value="1" 
    ng-false-value="0" 
    ng-checked="checkbox == 1" />

您可以使用 $ scope。$ watch 将它转换为数字

And you can use $scope.$watch to convert it to number

$scope.$watch(function(){
    return $scope.checkbox;
}, function(){
    $scope.checkbox = Number($scope.checkbox);
    console.log($scope.checkbox, typeof $scope.checkbox);
},true);

DEMO

这篇关于将ngTrueValue和ngFalseValue设置为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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