I have a "clear" button, once user hit it all the data in container,all binding and the radio buttons should be reset (like initially). Currently only the view becomes empty but the container has still the old value. How can I fix it?
<div class="field">
<textarea name="price" ng-model="list.price"></textarea>
</div>
<input type="radio" ng-model="list.phone" value="1" />cell
<input type="radio" ng-model="list.phone" value="2" />home
<button class="btn btn-primary btn-large center" type="reset" ng-click="">
Clear
</button>
In a model-driven form to reset the form we just need to call the function reset() on our myform model. The form now resets, all the input fields go back to their initial state and any valid , touched or dirty properties are also reset to their starting values.
Wrap your all input elements inside form tag so that It will automatically creates a top-level FormGroup instance. Update the form tag with a template reference variable, #form, and set its value as follows. @ViewChild(NgForm) form:NgForm; Finally you can call reset method on form instance.
$setPristine();Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false.
Resetting a form in template-driven approach: In template driven approach, we need to import NgForm from '@angular/forms' and we use [(ngModel)] directive for two way data-binding and we should also import FormsModule from '@angular/forms' in app. module. ts file.
Set ng-click
to some function, say reset()
<button class="btn btn-primary btn-large center"
type="reset"
ng-click="reset()">Clear
</button>
and then set the model to an empty object
$scope.reset = function() {
$scope.list = {};
}
Or, if $scope.list is prepopulated, you could do something like this (taken from angular docs):
function Controller($scope) {
$scope.master = {};
$scope.reset = function() {
$scope.list = angular.copy($scope.master);
};
$scope.reset();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With