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

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

问题描述

更新:对于最新的 Angular 版本,问题已经过时,请参阅 tsh 对这篇文章的评论

Update: question is obsolete for latest Angular version, see tsh's comment on this post

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

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 演示)

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')}}"

它们都不起作用.如何让 angular 将参数视为数字?

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

演示

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

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