我有一个问题,我试图将我的模型中的复选框的值发布到服务器并且由于该复选框尚未在表单上进行交互,angular 似乎没有为其分配值,当我询问复选框的值,它返回为未定义。
这是我的标记:
<div class="form-group">
<input id="templateDisable" type="checkbox" ng-model="template.disabled" />
<label for="templateDisable">Disabled</label>
</div>
这是我在 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
}
};
实际上,在我点击保存操作之前勾选然后取消勾选复选框会导致 template.disabled 属性为 false,这是我在没有任何手动干预的情况下所期望的结果。
我看过其他相关问题,例如AngularJS: Initial checkbox value not in model但肯定像简单的复选框之类的东西应该被烘烤吗?我不应该一定要编写指令来管理复选框吗?
最佳答案
这是每个设计。如果你想在你的模型上使用默认值,你应该在 Controller 中初始化它(推荐),或者使用 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>
关于javascript - AngularJS 复选框模型值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20743030/