AngularJS:ng-model 未绑定到 ng-checked 复选框 [英] AngularJS: ng-model not binding to ng-checked for checkboxes
问题描述
我在问这个问题之前提到了这个.
I referred to this before asking this question.
AngularJs 不绑定 ng-checked 和 ng-model
如果 ng-checked
在 html
端被评估为 true
,则 ng-model
不是更新.我不能按照上述问题的建议 ng-repeat
,因为我必须为每个复选框使用一些样式.
If ng-checked
is evaluated to true
on the html
side, the ng-model
is not updated. I can't ng-repeat
as suggested in the above question because I have to use some styling for each checkbox.
这是我创建的 plunker 来说明我的问题.
Here is the plunker that I have created to illustrate my problem.
http://plnkr.co/edit/YsOsPh3vjkPMUUDa6r2t
要查看我想要什么,请打开控制台,然后单击Submit
按钮.请不要选中任何复选框.
To see what I want, please open the console, and just click on Submit
button. Please don't check any checkboxes.
提前致谢!
推荐答案
ngModel
和 ngChecked
不能一起使用.
ngModel
and ngChecked
are not meant to be used together.
ngChecked
需要一个表达式,因此通过说 ng-checked="true"
,您基本上是说默认情况下将始终选中复选框.
ngChecked
is expecting an expression, so by saying ng-checked="true"
, you're basically saying that the checkbox will always be checked by default.
您应该能够只使用 ngModel
,绑定到模型上的布尔属性.如果你想要别的东西,那么你要么需要使用 ngTrueValue
和 ngFalseValue
(目前只支持字符串),或者编写你自己的指令.
You should be able to just use ngModel
, tied to a boolean property on your model. If you want something else, then you either need to use ngTrueValue
and ngFalseValue
(which only support strings right now), or write your own directive.
你到底想做什么?如果您只想默认选中第一个复选框,您应该更改您的模型——item1: true,
.
What is it exactly that you're trying to do? If you just want the first checkbox to be checked by default, you should change your model -- item1: true,
.
您不必提交表单来调试模型的当前状态,顺便说一句,您可以将 {{testModel}}
转储到您的 HTML(或 <pre>{{testModel|json}}</pre>
).此外,您的 ngModel
属性可以简化为 ng-model="testModel.item1"
.
You don't have to submit your form to debug the current state of the model, btw, you can just dump {{testModel}}
into your HTML (or <pre>{{testModel|json}}</pre>
). Also your ngModel
attributes can be simplified to ng-model="testModel.item1"
.
http://plnkr.co/edit/HtdOok8aieBjT5GFZOb3?p=preview
这篇关于AngularJS:ng-model 未绑定到 ng-checked 复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!