Ng-submit action called after ng-click
I am new to AngularJS. I'm trying the demo mentioned in O'Reilly's AngularJS book. I know that when there is one input field in a form, pressing the enter key inside that input will trigger both actions ng-click
and ng-submit
. However, in my case, I only have one input field, even if I don't press the enter key inside the input field, my ng-submit action is called every time I click the reset button. Here is the code.
<!DOCTYPE html>
<html ng-app="">
<head lang="en">
<meta charset="UTF-8">
<title>Form Submit Action</title>
</head>
<body>
<form ng-submit="requestFunding()"
ng-controller="FormController">
Estimate :
<input ng-model="estimate"/>
<br/>
Recommended :
{{recommended}}
<br/>
<Button>Fund My Start Up</Button>
<Button ng-click="reset()">Reset</Button>
</form>
<script src="Scripts/angular.js"></script>
<script>
function FormController($scope)
{
$scope.estimate = 0;
computeNeeded = function(){
$scope.recommended = $scope.estimate * 10;
};
$scope.$watch('estimate', computeNeeded);
$scope.requestFunding = function()
{
window.alert("Add More Customers First");
};
$scope.reset = function()
{
$scope.estimate = 0;
};
}
</script>
</body>
</html>
Is there a logical or conceptual error? Please also enlighten me on the correct way to submit and reset the form when I use AngularJS.
source to share
In the stardard html you need to set type="reset"
to indicate it is a reset button:
<button type="reset" ng-click="reset()">Reset</button>
But you will see a problem with this approach in angular as shown in the DEMO . When you click Reset
, the input is set to empty, not 0 as you indicate in your code:
$scope.reset = function() {
$scope.estimate = 0;
};
The reason for this issue is yours is being $scope.reset
run first and overwritten with the browser default action for the reset button (clear the login form).
In angular you need to do it differently, you need preventDefault
and use form.$setPristine()
to reset the input states of the form:
<form name="form" ng-submit="requestFunding()" ng-controller="FormController"> //give the form a name
Estimate :
<input ng-model="estimate" />
<br/>Recommended : {{recommended}}
<br/>
<button>Fund My Start Up</button>
<button ng-click="$event.preventDefault(); reset(); form.$setPristine();">Reset</button>
</form>
Output from the doc for $ setPristine :
Sets the form to its original state.
This method can be called to remove the 'ng-dirty' class and set the form to its pristine state (ng-pristine class). This method also applies to all controls contained in this form.
Setting a form back to a pristine state is often useful when we want to "reuse" a form after saving or resetting.
source to share