Angularjs Form Submit Example in Different Ways
As we know there are so many option to do any task, in same way using angularjs we can submit form in many ways.
What will we do :We will create a view with attribute ng-controller
in which we create form with single input text field when form is submitted then we will handle the form request in angularjs.
ng-submit handler is fired on form submission. This is a popular way to submit form in angularjs
You can define ng-submit
as element and also it can be define as attribute.
- <script>
- angular.module('mydemoapp', [])
- .controller('DemoController', ['$scope', function($scope) {
- $scope.list = [];
- $scope.text = 'Welcome to Expert PHP';
- $scope.doSomeAction = function() {
- if ($scope.text) {
- $scope.list.push(this.text);
- $scope.text = '';
- }
- };
- }]);
- </script>
- <form ng-submit="doSomeAction()" ng-controller="DemoController">
- Enter text and hit enter:
- <input type="text" ng-model="text" name="text" />
- <input type="submit" id="submit" value="Submit" />
- <pre>list={{list}}</pre>
- </form>
If you don't want to use ng-submit
and form should be submitted then use ng-click
event handler.
ng-click
is triggered when any element is clicked.
You can define ng-click
as element and also it can be define as attribute.
- <script>
- angular.module('mydemoapp', [])
- .controller('DemoController', ['$scope', function($scope) {
- $scope.list = [];
- $scope.text = 'Welcome to Expert PHP';
- $scope.doClickAction = function() {
- if ($scope.text) {
- $scope.list.push(this.text);
- $scope.text = '';
- }
- };
- }]);
- </script>
- <form ng-controller="DemoController">
- Enter text and hit enter:
- <input type="text" ng-model="text" name="text" />
- <input type="button" id="button" value="Submit" ng-click="doClickAction()" />
- <pre>list={{list}}</pre>
- </form>
If you are using Laravel to generate form then Laravel blade generate form action attribute and in that case angularjs won't process due to action attribute.In that scenario you can use $event
handler to stop the default action.
- <script>
- angular.module('mydemoapp', [])
- .controller('DemoController', ['$scope', function($scope) {
- $scope.list = [];
- $scope.text = 'Welcome to Expert PHP';
- $scope.doSomeAction = function(event) {
- event.preventDefault();
- if ($scope.text) {
- $scope.list.push(this.text);
- $scope.text = '';
- }
- };
- }]);
- </script>
- <form action="page.php" ng-submit="doSomeAction()" ng-controller="DemoController">
- Enter text and hit enter:
- <input type="text" ng-model="text" name="text" />
- <input type="submit" id="submit" value="Submit" />
- <pre>list={{list}}</pre>
- </form>