0

I have a form with a checkbox that binds to ng-model property. When I check the checkbox the value is set in the model but when its unchecked, the key and value are never set at all so it fails api validation.

<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();
        }
    }
]);

This is what the model looks like before it's saved:

{
    $resolved: true
    author: "asdag"
    content: "adfadsf"
    title: "adgadf"
    proto: ...
}

Why is post.is_visible undefined instead of being set to false? What can I do to make it set false?

1
  • normal form behavior ... unchecked checkboxes aren't sent to server in default browser submit process...so why would angular be any different? Sounds more like a server logic problem Commented Jul 24, 2015 at 19:25

1 Answer 1

1

try this

 <input type="checkbox" ng-model="post.is_visible"  ng-init="post.is_visible=false" />
Sign up to request clarification or add additional context in comments.

2 Comments

won't change the issue if you toggle the checkbox on and off
i don't know whether this will help you, i have used something like this ng-true-value="true" ng-false-value="false"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.