I am new to AngularJS. I am trying a demo mentioned in AngularJS book by O'Reilly.
I know that when there is one input field in the form, hitting enter key inside that input, would cause both ng-click
and ng-submit
action to be triggered. However, in my case, I have only one input field, even if I do not press enter key inside the input field, my ng-submit action is called everytime when i click on reset button.
Here is 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 any logical or conceptual mistake ? Please also enlighten my on the right way to submit and reset the form when I am using AngularJS.
instead of using ng-submit, use ng-click to call requestFunding(), it will solve your problem.
Give your buttons proper types to control if they are submitting the form - e.g:
In stardard html, you need to set
type="reset"
to indicate that this is a reset button:But you would see a problem with this approach in angular, as this DEMO shows. When you click
Reset
, the input is set to empty instead of 0 as you specify in your code:The reason for this problem is that your
$scope.reset
runs first and is overwritten by the default action of the browser for the reset button (clear the form inputs).In angular, you need to do differently, you need to
preventDefault
and useform.$setPristine()
to reset the form input states:DEMO
Quouted from the docs for $setPristine: