I've added validations for my form and I wanted it to trigger each and every validation when submit button is clicked. I tried googling for how to trigger them but it seems they are not working for me.
Here's my code for the form
<form id="CustomerForm" class="form-horizontal group-border stripped" name="CustomerDetails" novalidate ng-submit="CustomerDetails.$valid && AddCustomer()">
<div class="form-group" ng-class="{'has-error': CustomerDetails.cname.$invalid && !CustomerDetails.cname.$pristine}">
<label class="col-lg-2 col-md-3 control-label">Customer Name</label>
<div class="col-lg-10 col-md-9">
<input type="text" ng-model="CusDetails.cname" class="form-control" name="cname" id="cname" required />
<p ng-show="CustomerDetails.cname.$error.required && !CustomerDetails.cname.$pristine" class="help-block">Customer name required!</p>
</div>
</div>
<!--end of .form-group-->
<div class="form-group" ng-class="{'has-error': CustomerDetails.comname.$invalid && !CustomerDetails.comname.$pristine}">
<label class="col-lg-2 col-md-3 control-label">Company Name</label>
<div class="col-lg-10 col-md-9">
<input type="text" ng-model="CusDetails.comname" class="form-control" name="comname"id="comname" required />
<p ng-show="CustomerDetails.comname.$error.required && !CustomerDetails.comname.$pristine" class="help-block">Comapany name required!</p>
</div>
</div>
<!--end of .form-group-->
<div class="form-group" ng-class="{'has-error': CustomerDetails.ctel.$invalid && !CustomerDetails.ctel.$pristine}">
<label class="col-lg-2 col-md-3 control-label" for="">Telephone Number</label>
<div class="col-lg-10 col-md-9">
<div class="input-group input-icon">
<span class="input-group-addon"><i class="fa fa-phone s16"></i></span>
<input ng-model="CusDetails.tel" class="form-control" name="ctel" type="text" placeholder="(999) 999-9999" id="ctel" required >
<p ng-show="CustomerDetails.ctel.$error.required && !CustomerDetails.ctel.$pristine" class="help-block">Telephone number required!</p>
</div>
</div>
</div>
<!-- End .form-group -->
<div class="form-group" ng-class="{'has-error': CustomerDetails.email.$invalid && !CustomerDetails.email.$pristine}">
<label class="col-lg-2 col-md-3 control-label" for="">Email address</label>
<div class="col-lg-10 col-md-9">
<input ng-model="CusDetails.email" type="email" class="form-control" name="email" placeholder="someone#example.com" id="email" required >
<p ng-show="CustomerDetails.email.$error.required && !CustomerDetails.email.$pristine" class="help-block">Email is required!</p>
<p ng-show="CustomerDetails.email.$error.email && !CustomerDetails.email.$pristine" class="help-block">Please Enter valid email address.</p>
</div>
</div>
<!-- End .form-group -->
<div class="form-group">
<div class="col-lg-9 col-sm-9 col-xs-12">
<button name="btnSubmit" type="submit" class="btn btn-info pad"><span class="fa fa-user-plus"></span> Add Customer</button>
<button type="button" id="cancel" class="btn btn-default pad">Cancel</button>
</div>
</div>
</form>
UPDATE: I have change the code according to Adrian Brand but still no trigger. What am I doing wrong?
Here's my angularjs for the form. (controller)
(function () {
'use strict';
angular
.module('efutures.hr.controllers.customer', [])
.controller('AddCustomerController', AddCustomerController);
AddCustomerController.$inject = ['$scope', '$location', '$rootScope', '$http', 'CustService'];
function AddCustomerController($scope, $location, $rootScope, $http, CustService) {
(function initController() {
})();
$scope.AddCustomer = function () {
var CustomerDetails = {
cname: $scope.CusDetails.cname,
comname: $scope.CusDetails.comname,
tel: $scope.CusDetails.tel,
email: $scope.CusDetails.email
};
if ($scope.CustomerDetails.$valid) {
CustService.Customer(CustomerDetails, function (res) {
console.log(res);
$.extend($.gritter.options, {
position: 'bottom-right',
});
if (res.data == 'success') {
$.gritter.add({
title: 'Success!',
text: 'Successfully added the new customer ' + '<h4><span class="label label-primary">' + CustomerDetails.cname + '</span></h4>',
time: '',
close_icon: 'l-arrows-remove s16',
icon: 'glyphicon glyphicon-ok-circle',
class_name: 'success-notice'
});
$scope.CusDetails = {};
$scope.CustomerDetails.$setPristine();
}
else {
$.gritter.add({
title: 'Failed!',
text: 'Failed to add a new customer. Please retry.',
time: '',
close_icon: 'l-arrows-remove s16',
icon: 'glyphicon glyphicon-remove-circle',
class_name: 'error-notice'
});
}
});
}
}
}
})();
I even tried making the form submitted true, still didn't work.
The only thing that worked for me is the disabling the button until its validated but that isn't the requirement. I want it to trigger when the submit form is clicked. Help would be greatly appreciated.
In the click event where you wanted to trigger the validation, add the following:
vm.triggerSubmit = function() {
vm.homeForm.$setSubmitted();
...
}
This works for me. To know more about this click here : https://code.angularjs.org/1.3.20/docs/api/ng/type/form.FormController
Your problem lies in the fact that your submit button is not contained in the form so the form never gets submitted. You are just running the controller method via a click handler.
Form validation is not a controller concern and has no place in the controller. It is purely a view concern.
In your form you put a ng-submit="CustomerDetails.$valid && AddCustomer()" and take the click handler off the submit button and place the button row within the form. This way the view will only submit if the form is valid. Do not pollute your controllers with form validation and keep it all contained in your view. You should look into the controller as syntax and then you will not even have access to the $scope in your controllers.
Related
Using Laravel framework.
I don't get it. I have a hidden input with id = prime near the top.
<form name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
{{ csrf_field() }}
<input type="hidden" id="parking_lot_id" name="parking_lot_id" value="{{ $parking_lot_id }}">
<input type="hidden" id="booking_id" name="booking_id" value="{{ $booking_id }}">
<input type="hidden" id="Price" name="Price" value="{{ $Price }}">
<input type="hidden" id="prime" name="prime"> {{-- To be obtained --}}
<legend>電子發票 & TapPay 付款</legend>
<div class="form-group">
<label for="CustomerEmail" class="col-lg-3 col-md-3 col-xs-4">電子信箱</label>
<div class="col-lg-9 col-md-9 col-xs-8">
<input type="email" class="form-control" id="CustomerEmail" name="CustomerEmail" value="{{ old('CustomerEmail') }}">
</div>
</div>
<div class="form-group">
<label for="CustomerPhone" class="col-md-3 col-xs-4">手機號碼</label>
<div class="col-md-9 col-xs-8">
<input type="number" class="form-control" id="CustomerPhone" name="CustomerPhone" value="{{ old('CustomerPhone') }}">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-3 col-xs-offset-4 col-md-9 col-xs-8">
<select class="form-control" id="giveTongBian" name="giveTongBian">
<option value="no" #if(old('giveTongBian') === "no") selected #endif>不需統編</option>
<option value="yes" #if(old('giveTongBian') === "yes") selected #endif>輸入統編</option>
</select>
</div>
</div>
<div class="form-group" id="customerIdentGroup">
<label for="CustomerIdentifier" class="col-md-3 col-xs-4">統一編號</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerIdentifier" name="CustomerIdentifier" value="{{ old('CustomerIdentifier') }}">
</div>
</div>
<div class="form-group" id="customerNameGroup">
<label for="CustomerName" class="col-md-3 col-xs-4">買受人</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerName" name="CustomerName" value="{{ old('CustomerName') }}">
</div>
</div>
<div class="form-group" id="customerAddrGroup">
<label for="CustomerAddr" class="col-md-3 col-xs-4">地址</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerAddr" name="CustomerAddr" value="{{ old('CustomerAddr') }}">
</div>
</div>
<div class="tappay-form col-xs-offset-1 col-xs-10">
<h4 style="color: darkkhaki;">信用卡</h4>
<div class="form-group card-number-group">
<label for="card-number" class="control-label"><span id="cardtype"></span>卡號</label>
<div class="form-control card-number"></div>
</div>
<div class="form-group expiration-date-group">
<label for="expiration-date" class="control-label">卡片到期日</label>
<div class="form-control expiration-date" id="tappay-expiration-date"></div>
</div>
<div class="form-group cvc-group">
<label for="cvc" class="control-label">卡片後三碼</label>
<div class="form-control cvc"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Pay</button>
</div>
</div>
</form>
I then have a on submit event which does a few things. At the bottom is me updating the hidden input with id = prime.
$('form').on('submit', function (event) {
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
//Begin validation
var numOfNonEmptyFields = 0;
if(document.forms["paymentForm"]["CustomerEmail"].value != "") {
numOfNonEmptyFields++;
}
if(document.forms["paymentForm"]["CustomerPhone"].value != "") {
numOfNonEmptyFields++;
}
if(numOfNonEmptyFields == 0) {
errorMsg += "請輸入至少一個電子信箱或手機號碼.\n";
boolFlag = false;
}
//End validation
//Final steps: overall error message + success or fail case
if(boolFlag == false) {
alert("錯誤:\n" + errorMsg);
return false;
}
//Code for first part of form end
// fix keyboard issue in iOS device
forceBlurIos()
const tappayStatus = TPDirect.card.getTappayFieldsStatus()
console.log(tappayStatus)
// Check TPDirect.card.getTappayFieldsStatus().canGetPrime before TPDirect.card.getPrime
if (tappayStatus.canGetPrime === false) {
bootbox.alert({
title: "錯誤訊息",
message: "取得不了Prime.",
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
$("#prime").val(result.card.prime);
})
})
I've tested the hidden input with alert($("#prime").val()) directly after and it seems updated, however after submission, my Controller receives the value as null while other hidden input values are correct. So I suspect it's something got to do with the on submit event.
Added id attribute to the form element:
<form id="paymentForm" name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
Removed type from the button and added id:
<button id="submit-btn" class="btn btn-default">Pay</button>
Introduced a new click listener:
$(document).on("click","#submit-btn", function(event){
event.preventDefault();
validateAndSendForm();
});
Introduced a new function for the final form submit:
function submitForm(){
//do other stuff here with the finalized form and data
//.....
$( "#paymentForm" ).submit();
}
And put all of your old things into a new function as well:
function validateForm(){
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
...
...
...
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false;
}
$("#prime").val(result.card.prime);
//use when you are ready to submit
submitForm();
})
}
So, basically you will have a "submitForm" function that you can use whenever you are ready to submit the form.
Seems like TPDirect.card.getPrime is something that gets data asynchronously so the $('form').on('submit' function won't wait for it to finish.
I have a simple query submission form with name, email and query fields and a component with a controller function having the submit function to submit the form.
I am using ng-submit directive in the <form></form> tag to submit the user input and display a success message on submission.
below is the code for the respective files.
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div>
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService,$rootScope) {
var vm = this;
$scope.navigate = function(home){
$state.go(home)
};
$scope.saveform = function(){
$scope.name= vm.name;
$scope.email= vm.email;
$scope.query= vm.email;
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted."
};
$scope.user = userService;
};
//localStorage code
function userService($rootScope) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
UPDATE: On Submit, When I check the response in network tab in dev tools, I do not see the submitted values. All I see is the markup.
In your template, the name of the method is saveform:
ng-submit="saveform()"
But in your controller, it's save:
$scope.save = function() { ... }
Rename it to saveform:
$scope.saveform = function() { ... }
I want to apply required field validation on text box group in which at least one text box group must contain value.
in bellow image, details of at least one bank must be filled.
I have used jquery-form-validator plugin from http://www.formvalidator.net/#custom-validators and created custome validator as bellow, but Its not working.
$("#txtBankDetails")
.valAttr('error-msg', 'select atlest 1 bankname.');
$.formUtils.addValidator({
name: 'data-text-group',
validatorFunction: function (value, $el, config, language, $form) {
debugger
var isValid = true,
// get name of element. since it is a checkbox group, all checkboxes will have same name
elname = $el.attr('data-text-group'),
// get checkboxes and count the checked ones
$textBoxes = $('input[type=textbox][data-text-group^="' + elname + '"]', $form),
nonEmptyCount = $textBoxes.filter(function () {
return !!this.value;
}).length;
alert(nonEmptyCount);
if (nonEmptyCount == 0) {
isValid = false;
}
}
});
// Setup form validation only on the form having id "registration"
$.validate({
form: '#registration',
modules: 'date, security, file, logic',
validateOnBlur: true,
showHelpOnFocus: true,
addSuggestions: true,
onModulesLoaded: function () {
console.log('All modules loaded!');
},
onSuccess: function ($form) {
form.submit();
alert("sucess")
return false;
},
onError: function () {
alert("Error")
}
});
html code is,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/theme-default.min.css"
rel="stylesheet" type="text/css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<form id="registration" method="post" action="#Url.Action("NewRegistration", "StaticPage")" enctype="multipart/form-data" class='has-validation-callback'>
<div class="container">
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname1" data-text-group="BankName" placeholder="01. BANK NAME" data-validation-error-msg="select atlest 1 bankname.">
</div>
<div class="col-md-4">
<input class="nwresmainfild" name="BankACNo1" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input class="nwresmainfild" name="BankAddress1" placeholder="BANK ADDRESS">
</div>
</div>
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname2" data-text-group="BankName" placeholder="01. BANK NAME" data-validation-error-msg="select atlest 1 bankname.">
</div>
<div class="col-md-4">
<input name="BankACNo2" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input name="BankAddress2" placeholder="BANK ADDRESS">
</div>
</div>
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname3" data-text-group="BankName" placeholder="03. BANK NAME" >
</div>
<div class="col-md-4">
<input name="BankACNo3" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input name="BankAddress3" placeholder="BANK ADDRESS">
</div>
</div>
</div>
<input value="PROCESS & PRINT" class="green-btn uppercase" type="submit" id="btnSubmit" />
</form>
Form is not cleared after saved record in angularJs. I'm trying to reset form many ways, but form is not reset.
My angularjs version is 1.4.8.
This question is also a duplicate, but I tried what stack overflow users said. That has not worked for me.
Looking for a positive reply
Thank you.
Html code:
<form name="myForm" id="myForm" novalidate>
<input type="hidden" name="forumValue" ng-model="fid.forumValue"
id="forumValue" placeholder="fourm Id" />
<div class="form-group row">
<label for="inputAnswer" class="col-sm-2 col-form-label">Answer</label>
<div class="col-sm-10">
<textarea rows="10" name="answer" class="form-control"
ng-model="fid.answer" required></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<button type="button" class="btn btn-success"
ng-click="saveUserAnswer(fid)">Post Your Answer</button>
</div>
</div>
</form>
Controller Code:
$scope.saveUserAnswer = function(fid) {
UserRepository.saveUserAnswer(fid).then(
function(response) {
var status = response.message;
if (status == "success") {
alert("posted success");
$scope.UserAnswer=getUserOnIdAnswer(fid.UserValue);
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$state.go('UserAnswer');
}
else {
$scope.User=response;
alert("posted Fail,Please correct the details..!!");
}
});
};
Is your form wrapped in an ng-if statement? If so, the form might be inside a child scope, and you might try:
Option A
Replace your ng-if with an ng-hide.
Option B
Bind the form to an existing object on the parent scope:
$scope.myData = {};
$scope.saveUserAnswer = function(fid) {
...
};
Then in your HTML, refer to the form on the parent scope:
<form name="myData.myForm" id="myForm" novalidate>
</form>
Source: https://github.com/angular/angular.js/issues/15615
I have attempted to recreate your problem but without the call to the UserRepository just to confirm that we can set the form $pristine value to true and to reset the form.
<form name="form.myForm" id="myForm" novalidate>
<input type="hidden" name="forumValue" ng-model="fid.forumValue" id="forumValue" placeholder="fourm Id" />
<div class="form-grou`enter code here`p row">
<label for="inputAnswer" class="col-sm-2 col-form-label">Answer</label>
<div class="col-sm-10">
<textarea rows="10" name="form.myForm.answer" class="form-control" ng-model="fid.answer" required></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<button type="button" class="btn btn-success" ng-click="saveUserAnswer(fid)">Post Your Answer</button>
</div>
</div>
</form>
<pre>{{form.myForm.$pristine}}</pre>
and the controller code like so :
$scope.form = {};
$scope.saveUserAnswer = function(fid) {
$scope.form.myForm.$setPristine();
$scope.fid = {};
//omitted the user repository code
};
The above will set the pristine value of the form to true and also reset the value of fid on click of the button.
EDIT
Also the call to your repository function should be in this format:
UserRepository.saveUserAnswer(fid).then(
function(response){
//success
},
function(response){
//error
}
);
In controller try to add '$scope.fid.answer=null;' after scope.myForm.$setPristine();
like this.
$scope.saveUserAnswer = function(fid) {
UserRepository.saveUserAnswer(fid).then(
function(response) {
var status = response.message;
if (status == "success") {
alert("posted success");
$scope.UserAnswer=getUserOnIdAnswer(fid.UserValue);
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$scope.fid.answer=null;
$state.go('UserAnswer');
}
else {
$scope.User=response;
alert("posted Fail,Please correct the details..!!");
}
});
};
I´ve a simple 3 pages html. Index, contact and services. I call the templates views html with ng-view. All is fine. I see them with buttons navbar.
In contact.html, I want use the phpmailer and tutorial from "http://www.chaosm.net/blog/2014/05/21/angularjs-contact-form-with-bootstrap-and-phpmailer/".
In my controller, I paste the code JS in new controller, and in my html file the same form fron tutorial. After differents tests, I reach the controller working but when I pulse the input submit:nothing happen and doesn´t send anything.
I change the path relative to my exampledomain.net/js/contact-form.php in the code controller. Change so in contact-form the path for the call to PHPMailerAutoload.php.
In the contactform.html, I put in first div the call to controller ) and same form example.
In contact-form.php all is the same like the tutorial, only I change the path like I write before).
Is posible the post form doesn´t work because I use ng-view? Someone have 1 idea why contact-form.php seem not running?
I´m very beginner in Angular JS. thanks
The code of the unique controller I have (for routing and form phpmailer):
//Creo modulo y su nbre + establecer function routage
var AppSol = angular.module('AppSol', ['ngRoute']);
//Configure routage
AppSol.config(function($routeProvider){
$routeProvider
//Indico links pages nav
.when ('/',{
templateUrl:'templates/home.html',
controller:''
})
.otherwise ({
redirectTo:"/"
})
.when ('/Inicio',{
templateUrl:'templates/home.html',
controller:'MainCtrl'
})
.when ('/Contacto',{
templateUrl:'templates/contacto.html',
controller:'ContactController'
})
.when ('/Servicios',{
templateUrl:'templates/servicios.html',
controller:'ServCtrl'
});
});
//Creo controller and lo injecto
AppSol.controller ('MainCtrl', function($scope){
//Probar que funciona con mensaje
$scope.titulo="MY TITLE";
});
//Creo controller and lo injecto
AppSol.controller ('ServCtrl', function($scope){
//Probar que funciona con mensaje
$scope.message='';
$scope.titulo='SECOND TITLE'
});
//Creo controller and lo injecto
AppSol.controller ('ContactController', function ($scope, $http) {
$scope.titulo='TEST1 CALL CONTACT CONTROLLER'
//$scope.result = 'Hidden'
$scope.resultMessage='Test2 with Result control - I see this mensaje.';
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : 'http://exampledomain.net/test/js/contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed :( Please fill out all the fields.';
$scope.result='bg-danger';
}
}
});
Of course:
<div class="jumbotron" ng-app="AppSol">
<div class="container">
<div id="corte"></div>
<div class="vertical-middle">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Contact Form</h2> <strong>{{titulo}} for test controller form</strong>
</div>
<div ng-controller="ContactController" class="panel-body">
<form ng-submit="submit(contactform)" name="contactform" method="post" action="" class="form-horizontal" role="form">
<div class="form-group" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<label for="inputName" class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="Your Name" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<label for="inputSubject" class="col-lg-2 control-label">Subject</label>
<div class="col-lg-10">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<label for="inputMessage" class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">
Send Message
</button>
</div>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
</div>
</div>
</div>
</div>
View is ok, so you can add error to your $http promise, and see what is the server response.