Form and Ng-Submit in Angular Js
In this blog, I’m explaining how to create a form and submit
it using the angular js.
Example
First create an index.html page and the reference of
angular.min.js file like this:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Ngsubmit</title>
<script src="~/Scripts/angular.min.js"></script>
<body>
</body>
</html>
Now add the <script> tag in the head section of the
page write the following code:
<script>
var app = angular.module("myApp", []);
app.controller("myController", function ($scope) {
$scope.names = [{ name: "Sumit" }];
$scope.addValue = function () {
$scope.names.push($scope.newData);
$scope.newData = '';
}
});
</script>
Here I have create the controller named “myController”, and
it has one property names
which is an array and a method addValue() : used to add the value in the names.
Now in the <body> tag :
<body ng-controller="myController
as ctrl">
<div>
<div>
<ul>
<li ng-repeat="n in
names">{{$index + 1}} - {{n.name}}</li>
</ul>
<p>Total Entry : {{names.length}}</p>
</div>
<div>
<form ng-submit="addValue()">
<input type="text" ng-model="newData.name"
/>
<input type="submit" value="add" />
</form>
</div>
</div>
</body>
In the <body> add the “myController” controller using the ng-controller
directive.
Ng-repeat directive will display all the values in the
names.
$index will show the index of the object in the array. It
starts with 0.
In the angular expression, names.length will display the total number of
objects in the array.
Ng-submit
directive will submit the form to the addValue() method.
Output
Run the application:
Enter any name in the textbox and click on add button:
This will add the name in the array.
Thanks for posting this article sir... i regularly follow u.... your article is really helpful for beginners such as me...
ReplyDeleteThanks ajeet
Delete