Reputation: 5084
I have a form with a checkbox and I want to check its value on submit:
html:
<form class="form-horizontal" role="form" name="AddUserForm" ng-submit="submit(AddUserForm)">
...
<div class="form-group">
<label for="adduser-email" class="col-xs-2 col-xl-2 control-label">email</label>
<div class="col-xs-10 col-xl-10">
<input type="email" placeholder="email" id="adduser-email" ng-model="AddUserForm.email" required>
</div>
</div>
<div class="col-xs-12 col-xl-12">
<input id="adduser-mailinglist" type="checkbox" ng-model="AddUserForm.mailinglist">Add to mailing list</input>
</div>
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10 col-xl-offset-2 col-xl-10">
<button class="blue-button" type="submit" class="btn btn-default">Add User</button>
</div>
</div>
</form>
The JS:
$scope.submit = function(AddUserForm) {
console.log(AddUserForm.mailinglist);
};
I'm getting undefined
The text input is fine and exists in the form model
Made a plunkr: http://plnkr.co/edit/NKow0isUCp8PZy90drmA
Upvotes: 0
Views: 3211
Reputation: 718
As others have already provided a working plnkr, I will just let you know why your original didn't work. When creating properties without using dot notation, i.e. mailinglist
instead of AddUserForm.mailinglist
you are creating this property on the view's scope instead of getting the controller's scope. Use dot notation or Controller As to get at the controller's scope.
Check out this video by Egghead.IO for a more thorough explanation: AngularJS - The Dot
Upvotes: 0
Reputation: 92893
You just need to initialize the checkbox's model in your controller:
$scope.mailinglist = false;
Upvotes: 1
Reputation: 536
Updated answer:
Demo: http://jsfiddle.net/0ukwaug4/
Here's the update html, update submit(AddUserForm) to just submit(), the object is already defined in the scope level:
<form class="form-horizontal" role="form" name="AddUserForm" ng-submit="submit()">
...
<div class="form-group">
<label for="adduser-email" class="col-xs-2 col-xl-2 control-label">email</label>
<div class="col-xs-10 col-xl-10">
<input type="email" placeholder="email" id="adduser-email" ng-model="AddUserForm.email" required>
</div>
</div>
<div class="col-xs-12 col-xl-12">
<input id="adduser-mailinglist" type="checkbox" ng-model="AddUserForm.mailinglist">Add to mailing list</input>
</div>
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10 col-xl-offset-2 col-xl-10">
<button class="blue-button" type="submit" class="btn btn-default">Add User</button>
</div>
</div>
</form>
The javascript:
$scope.submit = function() {
console.log($scope.AddUserForm.mailinglist);
};
You'll get undefined
when it is unchecked, but it'll be true
when it is checked.
gl
Upvotes: 0