问题
I need some advice on how to properly reset a form in Angular JS. I'm having my form's data pushed to a object called .services, but every time I hit submit I would like for that form (text input and checkboxes) to be reset.
My form looks like this:
<div ng-app="app">
<div ng-controller="MainCtrl">
<form role="form" ng-submit="createService(newService)">
<div class="form-group">
<label for="serviceName">Name of Service</label>
<input id="serviceName" type="text" ng-model="newService.name">
</div>
<label ng-repeat="sector in sectors" for="{{sector}}">
<input type="checkbox" id="{{sector}}" value="{{sector}}" ng-model="newService.sectors[sector]">{{sector}}</label>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<section class="row well live-preview" ng-repeat="service in services">
<h3><a href="/">{{service.name}}</a></h3>
<ul class="list-unstyled">
<li ng-repeat="(sector, state) in service.sectors"> <span class="label label-primary" ng-show="state">{{sector}}</span>
</li>
</ul>
</section>
</div>
</div>
And my JS:
angular.module('app', [])
.controller('MainCtrl', function ($scope) {
$scope.sectors = ['health', 'social', 'education'];
$scope.services = [{
'name': 'Hernia Repair',
'sectors': {
'health': true
}
}, {
'name': 'Cancers',
'sectors': {
'health': true,
'social': true,
'education': true
}
}];
function createService(service) {
$scope.services.push(service);
}
$scope.createService = createService;
});
I tried creating a resetForm() function that sets the name and sector to empty strings, but then I was having some weird problems where the submitted values of the checkboxes weren't being properly set.
Any help with this is appreciated.
Thanks in advance.
Updated:
Would something like this work?
function resetForm() {
$scope.newService = {
name: '',
sector: {}
};
}
回答1:
Have you tried giving the form a name then calling $setPristine()?
Then call $scope.serviceForm.$setPristine();
回答2:
Why are you setting it to an empty string? Set new services to an empty object. You are using ng-model which should be able to set the key and value for you. Unless you want default values for the checkbox's in which you can set it to an object with the default values in there.
来源:https://stackoverflow.com/questions/26372791/reset-form-in-angularjs