本文介绍了AngularJS:反转复选框状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知何故,通过 Angular 的魔力,如果您使用 ng-model 并为其提供一个布尔值,那么您的复选框将在该布尔值为真时被选中,如果为假则不选中.

Somehow, through the magic of Angular, if you use ng-model and provide it a boolean, your checkbox will be checked if said boolean is true, and unchecked if false.

<input type="checkbox" ng-model="video.hidden">

虽然仅此一项就相当令人困惑,但我实际上是在尝试反转选中状态,因为与 todo.done 表示框被选中的 todo 示例不同,我的模型更像是 todo.incomplete.

While this alone is fairly baffling, I'm actually trying to reverse the checked state, because unlike the todo example where todo.done means the box gets checked, my model is more like todo.incomplete.

不幸的是,我的第一个猜测没有奏效:

Unfortunately my first guess didn't work:

<input type="checkbox" ng-model="!video.hidden">

我处于模型已被指示给我的位置,因此我无法更改它并且不想在客户端上对其进行按摩(因为我将客户端对象发送回服务器,因为它运行在受信任的环境中).

I'm in a position where the model has been dictated to me, so I can't change it and don't want to have to massage it on the client (because I'm sending client objects back to the server, since it's running in a trusted environment).

更新

这适用于 1.3 并且不给你字符串(1.2.xxx 给你字符串而不是布尔值):

This works in 1.3 and doesn't give you strings (1.2.xxx gave you strings instead of booleans):

<input type="checkbox" ng-model="video.hidden" ng-true-value="false" ng-false-value="true">

推荐答案

你现在可以做到,而无需自定义指令,角度支持 ng-true-valueng-false-值

You can make that now without a need of custom directive, angular support ng-true-value and ng-false-value

https://docs.angularjs.org/api/ng/input/输入[复选框]

你的例子现在应该可以工作了

your example should work now<input type="checkbox" ng-model="video.hidden" ng-true-value="false" ng-false-value="true">

这篇关于AngularJS:反转复选框状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 16:51