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: {} }; }
source share