Reset Form in AngularJS

I need advice on the correct form reset in Angular JS. I have form data that has been transferred to an object named .services , but every time I click submit, I would like this form (text input and checkboxes) to be reset.

My form is as follows:

 <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 to create a resetForm() function that sets name and sector to empty lines, but then I had some strange problems when the presented flag values ​​were set incorrectly.

Any help with this is appreciated.

Thanks in advance.

Updated:

Something like this work?

 function resetForm() { $scope.newService = { name: '', sector: {} }; } 
0
source share
2 answers

Have you tried giving the form a name and then calling $ setPristine ()?

Then call $ scope.serviceForm. $ setPristine ();

+1
source

Why are you setting it to an empty string? Install new services on an empty object. You are using an ng model that should be able to set the key and value for you. If you do not need the default values ​​for the check box, in which you can set it to an object with default values ​​there.

0
source

Source: https://habr.com/ru/post/1235761/


All Articles