javascript AngularJS 复选框模型值未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20743030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS checkbox model value is undefined
提问by A. Murray
I have a problem where I'm attempting to post the value of a checkbox in my model to the server and as the checkbox has not been interacted with on the form, angular seems to have not assigned it a value, when I ask for the value of the checkbox it comes back as undefined.
我有一个问题,我试图将模型中复选框的值发布到服务器,并且由于该复选框尚未在表单上进行交互,因此 angular 似乎没有为其分配值,当我要求复选框的值返回为未定义。
Here is my markup:
这是我的标记:
<div class="form-group">
<input id="templateDisable" type="checkbox" ng-model="template.disabled" />
<label for="templateDisable">Disabled</label>
</div>
And here's a reduced version of my save action on my controller:
这是我在控制器上保存操作的简化版本:
$scope.save = function (form) {
if (form.$valid) {
var formData = new FormData();
// this is the problem line of code
formData.append("disabled", $scope.template.disabled);
// ... some other stuff
}
};
Actually, ticking then unticking the checkbox before I hit the save action results in the template.disabled property being false, which is what I would have expected without any manual intervention.
实际上,在我点击保存操作之前勾选然后取消勾选复选框会导致 template.disabled 属性为 false,这是我在没有任何手动干预的情况下所期望的。
I've seen other related questions, e.g. AngularJS: Initial checkbox value not in modelbut surely stuff like a simple checkbox should be baked in? I shouldn't have to be writing directives to manage checkboxes surely?
我见过其他相关的问题,例如AngularJS: Initial checkbox value not in model但肯定像简单的复选框这样的东西应该被烘焙?我肯定不必编写指令来管理复选框吗?
回答by Stewie
This is per design. If you want a default value on your model than you should initialise it inside the controller (recommended), or make use of ng-init
.
这是每个设计。如果您想要模型的默认值,那么您应该在控制器内部初始化它(推荐),或者使用ng-init
.
app.controller('AppController',
[
'$scope',
function($scope) {
$scope.template = {
disabled = false
};
}
]
);
<div class="form-group">
<input type="checkbox" ng-model="template.disabled" ng-init="template.disabled=false" />
<label>Disabled</label>
</div>
回答by Neil Atkinson
The following will always set the state back to "unchecked" when the page is loaded (or refreshed). In other words it will overwrite the user's actual selection whenever the page is refreshed.
当页面加载(或刷新)时,以下内容将始终将状态设置回“未选中”。换句话说,无论何时刷新页面,它都会覆盖用户的实际选择。
<input type="checkbox" ng-model="template.disabled"
ng-init="template.disabled=false" />
If, however, you want the checkbox state set to a default state initially andyou also want it to remember user interactions, then the following is what you want.
但是,如果您希望复选框状态最初设置为默认状态,并且您还希望它记住用户交互,那么以下就是您想要的。
<input type="checkbox" ng-model="template.disabled"
ng-init="template.disabled = template.disabled || false" />