Use of ng-submit instead of form submit with action


ng-submit binds an expression to submit event of a form. This prevents the default action of the form which passes parameters to the address specified in the action attribute , if the form does not contain an action attribute. there is a very interesting article about use of Ajax in an Ajax form to submit data here. I very much encourage you to take a look there to fully utilize. here I’m giving you an example of how to use the submit form. First the HTML code:

[html]
<!doctype html>
<html ng-app=”myApp”>
<head>
<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css” rel=”stylesheet” crossorigin=”anonymous”>
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js”></script>
</head>
<body>
<form ng-submit=”submit()” ng-controller=”SubmitController”>
Add names to People array:
<input type=”text” ng-model=”person.name” name=”person.name” /><br/>
<input type=”submit” name=”person.name” value=”Submit” />
<p>people={{people}}</p>
<ul ng-repeat=”(index, object) in people”>
<li>{{ object.name }}</li>
</ul>
</form>
</body>
</html>
[/html]

now it’s time to add angular code to manage the submition. I’m gonna create a controller, let’s calling it “SubmitController”, to handle server objects for the app. I’m adding server object called person which is empty at the beggining. then a people array to capture people’s names from the input in the view (HTML). now that we have necessary elements, I need to create a function to handle the submission function. you can find the code below:


angular.module('myApp', [])
.controller('SubmitController', function($scope) {
$scope.person = {
name: null
};
$scope.people = [];
$scope.submit = function() {
if ($scope.person.name) {
$scope.people.push({name: $scope.person.name});
$scope.person.name = '';
}
};
});

Ramin Ahmadi
I am a full-stack front end developer with over 5 years experience in web design and development. I have worked with a wide variety of environments and languages including Angular, TypeScript, NodeJS, Restful API, Microservices, Atomic design, JQuery, Material design, Progressive Web Apps, DevOps, and many Azure tools. I make it a goal to automate myself out of routine tasks in my daily work. My motto is, ‘write human readable code, lean and clean’.

Comments 1

Your email address will not be published. Required fields are marked *

Use of ng-submit instead of form submit with action

log in

Captcha!

reset password

Back to
log in
Choose A Format
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
List
The Classic Internet Listicles
Image
Photo or GIF
Gif
GIF format