Ayan Ayan - 4 months ago 21
HTML Question

Unable to trigger submit in angularJS from a single button

Using

ng-submit
I have a form submission callback namely
submitFN
. Have 2 buttons:


  • Fund my startup!

  • Reset



My desirable output is on clicking the reset button, the input field gets 0. And on clicking "Fund my startUp" it shows an alert. How to attain this?

Problem:
Both the buttons are triggering the submitFN. Unable to reset.

Code:



<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js">


</script>
<script>
var mainApp = angular.module("mainApp", []);

mainApp.controller('startUpController', function($scope) {
$scope.funding = {
startingEstimate: 0
};

$scope.calculate = function () {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
};

$scope.submitFN = function () {
window.alert('Go and find more customers.')
}

$scope.resetFN = function () {
$scope.startingEstimate = 0;
}
});

</script>
</head>

<body>
<div ng-app='mainApp'>
<form ng-submit="submitFN()" ng-controller="startUpController">
Starting: <input type="text" ng-change="calculate()" ng-model="funding.startingEstimate"/>
Recommended: {{funding.needed}}
<button>Fund my startup!</button>
<button ng-click="resetFN()">Reset</button>
</form>
</div>
</body>

</html>





I am entirely novice in angularJS and any help is highly appreciable. Thanks in advance.

UPDATE
One of code I tried:



<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js">


</script>
<script>
var mainApp = angular.module("mainApp", []);

mainApp.controller('startUpController', function($scope) {
$scope.funding = {
startingEstimate: 0
};

$scope.calculate = function () {
$scope.funding.needed = $scope.funding.startingEstimate * 10;
};

$scope.submitFN = function () {
window.alert('Go and find more customers.')
}

$scope.resetFN = function () {
$scope.startingEstimate = 0;
}
});

</script>
</head>

<body>
<div ng-app='mainApp'>
<form ng-submit="submitFN()" ng-controller="startUpController">
Starting: <input type="text" ng-change="calculate()" ng-model="funding.startingEstimate"/>
Recommended: {{funding.needed}}
<button>Fund my startup!</button>
<button type = "button" ng-click="resetFN()">Reset</button>
</form>
</div>
</body>

</html>




Answer

By default the button type is submit, so you the 2nd button also has button type submit. If you don't want to submit a form on that button, you should explicitly make that button type as a button

type="button"

Also you had mistake in resetFN code, It should be modify a value which is assigned to ng-model

    $scope.resetFN = function () {
        $scope.funding.startingEstimate = 0;
    }