我有一个带有复选框的表单,该复选框绑定到ng-model属性。当我选中复选框时,该值在模型中设置,但是当未选中时,键和值根本不会被设置,因此它无法验证api。
<div class="form-group">
<label for="title">Title</label>
<input type="text" ng-model="post.title" placeholder="Post title..." />
</div>
<div class="form-group">
<label for="author">Author</label>
<input type="text" ng-model="post.author" placeholder="Your name" />
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea ng-model="post.content"></textarea>
</div>
<div class="form-group">
<label for="visible">Visible?</label>
<input type="checkbox" ng-model="post.is_visible" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Save" />
</div>
blogModule.controller('PostCreateController', ['$scope', '$stateParams', 'PostResource',
function ($scope, $stateParams, PostResource) {
$scope.post = new PostResource();
$scope.addPost = function () {
console.log($scope.post); // post.is_visible is undefined
//$scope.post.$save();
}
}
]);
这是模型在保存之前的样子:
{
$resolved: true
author: "asdag"
content: "adfadsf"
title: "adgadf"
proto: ...
}
为什么post.is_visible未定义而不是设置为false?我该怎么办才能把它设为假?
答案 0 :(得分:1)
试试这个
<input type="checkbox" ng-model="post.is_visible" ng-init="post.is_visible=false" />