angular form validation not working on form submitting - angularjs

I'm new in angularJS. My form doesn't validate on submit. I use angular-validation module downloaded from bower. How can I validate form on submit button?
I use refrence from https://github.com/huei90/angular-validation/blob/master/API.md
My form is like that:
<div ng-controller="nameController">
<form name="myForm" ng-submit="submitForm()">
<label for="ud_fname"></label>
<input
type="text"
id="ud_fname"
name="ud_fname"
placeholder="First Name"
ng-model="form.ud_fname"
valid-method="blur"
validator="required"
required-error-message="Required"
>
<label for="ud_lname"></label>
<input
type="text"
id="ud_lname"
name="ud_lname"
placeholder="Last Name"
ng-model="form.ud_lname"
valid-method="blur"
validator="required"
required-error-message="Required"
>
<input type="submit" value="Add" class="pure-button" />
<input type="reset" value="Reset" class="pure-button" />
</form>
My Controler is like that:
app.controller('nameController', function ($scope, $http) {
// insert record
$scope.submitForm = function (){
var url= 'functions/insert.php';
var data = {
ud_fname: $scope.form.ud_fname,
ud_lname : $scope.form.ud_lname,
};
console.log(data);
$http({
url: url,
data: data,
method: 'post'
}).success(function (response){
console.log(response);
});
};
});

You need to validate on ng-submit & don't call an submitForm if its not valid form
ng-submit="myForm.$valid && submitForm()"

You need to validate the form in your controller as well. Also, it would be better if you pass the form (user) as a parameter. If you are writing unit tests (which you should), it would be easier to test your method easily in that case as there will be no coupling with $scope.
P.S. Migrate your code to controllerAs syntax, you won't regret it.
$scope.submitForm = function (user, isValid){
if (isValid) {
var url= 'functions/insert.php';
var data = {
ud_fname: user.ud_fname,
ud_lname : user.ud_lname,
};
console.log(data);
$http({
url: url,
data: data,
method: 'post'
}).success(function (response){
console.log(response);
});
}
};
And your form will become:-
<form name="myForm" ng-submit="submitForm(form, myForm.$valid)">
.....
</form>

Related

angular js search bar, returns only data I entered into search bar

I am trying to enter a country into a search bar, use ng-click or ng-submit to return only the data for the country i entered into the search bar. right now when i submit, i get every country returned and then i can filter to get the country i want. I have all my data in mongolab, i use node js to get my data to my angular js service, then i have an angular js controller that sends data to the view i want. I am using anguler ui router. Here is my service:
angular.module('TravelSite').service('countryService', ['$http', '$q', function($http, $q) {
this.getCountry = function() {
var dfd = $q.defer();
$http({
method: 'GET',
url: '/country'
}).then(function(response) {
console.log(response.data);
dfd.resolve(response.data);
}, function(err) {
console.log('Error: ' + err);
});
return dfd.promise;
};
this.addCountry = function(body) {
var dfd = $q.defer();
$http({
method: 'POST',
url: '/country',
data: body
}).then(function(response){
console.log(response.data);
dfd.resolve(response.data);
}, function(error) {
console.log('error: ' + error);
});
return dfd.promise;
};
}]);
here is my controller:
angular.module('TravelSite').controller('CtrlCountry', function($scope, countryService) {
$scope.addCountry = function(country, cb) {
countryService.addCountry(country).then(function(res) {
});
}
$scope.getCountry = function() {
countryService.getCountry().then(function(dataFromService) {
$scope.countries = dataFromService;
});
}
});
here is my view:
<div>
<div>
<input type="text" ng-model="search.name">
<input type="text" placeholder="name" ng-model="country.name"/>
<input type="text" placeholder="population" ng-model="country.population"/>
<input type="text" placeholder="travel warning" ng-model="country.travel_warning"/>
<input type="text" placeholder="visa" ng-model="country.visa"/>
<input type="text" placeholder="vaccinations" ng-model="country.vaccinations"/>
<button ng-click="addCountry(country)">Create Country</button>
</div>
<form ng-submit="getCountry()">
<input type="text" ng-model="country.name">
<input type="submit" value="Search">
</form>
<button ng-click="addCountry(country)">Create Country</button>
<ul>
<li ng-repeat="country in countries | filter:search">{{country.name}}
{{country.population}} {{country.travel_warning}} {{country.visa}} {{country.vaccinations}}</li>
</ul>
</div>
I have only been coding for about a month, if anyone can help me, i will be extremely grateful.
thanks, and sorry in advance about the terrible looking code.
I'm new to Angular too. :)
I have some code that does exactly the same. I get a lot of info and, then, filter out only what I want.
Whant you can do to filter is to just do some changes on your view.
On your search input box, you can just do this:
<input type='text' ng-model='search'>
Then, on your ng-repeat, you may use:
<li ng-repeat="country in countries | filter: {name: search}">
If you want to filter all the fields, you may use this instead:
<li ng-repeat='country in countries | search'>
Hope it help. :)

AngularJS $http post request being cancelled

I'm trying to send a post form to a PHP script, and every time, the POST request shows as canceled.
My controller looks like this:
var authenticationControllers = angular.module('authenticationControllers', []);
authenticationControllers.controller('Authentication', ['$scope', '$http', function($scope, $http) {
$scope.WPlogin = function () {
var mydata ={
'action': 'ajaxlogin',
'username': $scope.user.username,
'password': $scope.user.password,
'security-login': pluginParams.nonce,
'_wp_http_referer': '/s/play/'
};
$http({
method: 'POST',
url: $scope.ajaxURL, //This is defined earlier, I'm sure this is valid
data: jQuery.param(mydata),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
console.log(data.message);
}).error(function(e){alert('error')});
};
}]);
And the form looks like this:
<div class="white-popup mfp-hide" id="login-modal" ng-controller="Authentication">
<form name="loginform" id="loginform" novalidate>
<h1>Login</h1>
<p class="status"></p>
<label for="username">Username</label>
<input id="username" type="text" name="username" ng-model="user.username" ng-required="true">
<label for="password">Password</label>
<input id="password" type="password" name="password" ng-model="user.password" ng-required="true">
<a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a>
<button class="submit_button" ng-disabled="loginform.$invalid" ng-click="WPlogin()" type="submit" name="submit"> Login</button>
</form>
</div>
Whenever I try to submit the form, the error alert pops up, but no console errors. Then, the page reloads, and I can see the form parameters in the URL (like a get request), and if I then submit my form (without deleting the get parameters), then the request is a success.
Can anyone tell me what I'm doing wrong?
Update
I added $event.preventDefault(); to the form (passing $event from the form), and now it all works as expected, but I don't understand, why do I need that? I thought AngularJS would automatically prevent the form submission.

ng-click event is not firing on button click?

i'm creating web application in Angularjs i write code in separate .js file for log in from database
is is execute on page load but not triggering on button click,
my .js code is:
var adminModule = angular.module('angApp', []);
//Defining a Angular Controller
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
Login();
function Login(U_Name, U_PWD) {
debugger;
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name, User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
}).error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
}]);
and my view as what i'm using for binding this using Angularjs here is an issue above code is working on page load but don't work on button click, the code i use is:
<div class="admin-login" ng-controller="AdminCtrl" ng-app="angApp">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
anyone please help me what i miss here so i'm not able to trigger ng-click event on button click
thanks in advance.
Your Login function needs to be on a scope. Right now, its essentially a private function:
$scope.Login = function () {
...
}
assign function to a scope variable.
var adminModule = angular.module('angApp', []);
//Defining a Angular Controller
adminModule.controller('AdminCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.Login = function (U_Name, U_PWD) {
debugger;
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name, User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
}).error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
$scope.Login();
}]);
Edited:
try to use this html code,but i am not sure.it may be that both ng-init and ng-controller are in same div and ng-controller load first after that ng-init :
<div ng-app="angApp">
<div class="admin-login" ng-controller="AdminCtrl" >
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>

how to send values from view controls to angularjs controller..?

In my Angularjs MVC application i write code for lo-gin which accept values from two text boxes as user name & password
my Angularjs controller code is as which works fine but problem with view
$scope.Login = function Login(U_Name, U_PWD) {
//Defining the $http service for login the admin user
$http({
method: 'POST',
url: '/Admin/IsAuthenticate',
data: { User_Name: U_Name,
User_PWD: U_PWD }
}).success(function (result) {
if (result == true) {
alert('user is valid');
}
else {
alert('unauthorised access!');
}
})
.error(function (error) {
//Showing error message
$scope.status = 'Unable to connect' + error.message;
});
}
this code is executing on ng-click event but doesn't accept values from input boxes
my view code is as:
<div ng-app="angApp">
<div ng-controller="AdminCtrl">
<div class="admin-login">
<h2>using angularjs</h2>
<input type="text" id="txtUserAng" placeholder="User Name" ng-model="U_Name" />
<input type="password" id="txtPWDAng" placeholder="Password" ng-model="U_PWD" />
<input type="button" id="login" value="login" ng-click="Login()" />
</div>
</div>
</div>
Your problem is that you are not passing U_Name, U_PWD variable to Login function. You need to pass input values to your function.
There are 2 ways of achieving it.
First, Pass the model directly to function like
<input type="button" id="login" value="login" ng-click="Login(U_Name, U_PWD)" />
Second, Use $scope.U_Name and $scope.U_PWD
$scope.Login = function() {
var U_Name = $scope.U_Name,
U_PWD = $scope.U_PWD
}
In controller get this
this example without set login parametr
$scope.Login = function Login() {
var U_Name = $scope.U_Name;
var U_PWD = $scope.U_PWD;
console.log($scope.U_Name);
console.log($scope.U_PWD);
}
And you can set login function parrameters that model
<input type="button" id="login" value="login" ng-click="Login(U_Name, U_PWD)" />
use this
data:
{
User_Name: $scope.U_Name,
User_PWD: $scope.U_PWD
}

Submit form with ng-submit and trigger synchronous post request

I have a form that I want to trigger validation on when the user clicks submit. If the validation fails, then suitable error messages are displayed. This much works.
However if the validation passes I want the form to submit a synchronous POST request with full page reload as if the action and method parameters were set as usual.
How does one achieve trigger the normal post action (not AJAX) from the ng-submit function on the AngularJS scope?
My form of course looks basically like the following:
<form id="myForm" name="myForm" ng-submit="formAction(this, models)">
...
<input type="submit" value="Submit">
</form>
The best I can think of is to mirror the contents of the form with another hidden form submitting that one, but there must be a better way!
TO CLARIFY: If validation passes, I need the form submission to essentially behave like a normal synchronous post form submission which lands the user at the page returned by the server from the post request.
http://plnkr.co/edit/cgWaiQH8pjAT2IRObNJy?p=preview
Please check this plunkr
Basically what I am doing is passing the $event object. form is the target of the event object, and we can submit it.
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function($event) {
if ($scope.text) {
$scope.list.push(this.text);
if(this.text === 'valid'){
$event.target.submit();
}
$scope.text = '';
}
};
}
Try inside formAction after you've submitted the data:
$route.reload();
I dont think you need to do a full page refresh. You have a single page app I am assuming; use it. Try something like this:
<section class="contact">
<article>
<h1>Contact</h1>
<form role="form" name="contactForm" ng-submit="formSubmit(contactForm)">
<div class="form-group">
<input class="form-control" ng-model="name" name="name" id="name" type="text" placeholder="Name" required/>
</div>
<div class="form-group">
<input class="form-control" ng-model="email" name="email" id="email" type="email" placeholder="Email Address" required/>
</div>
<div class="form-group">
<textarea class="form-control" ng-model="message" name="message" id="message" rows="5"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Send Message</button>
<a class="btn btn-default btn-lg" href='mailto:me#something.net'>Or email me</a>
</div>
</form>
</article>
'use strict';
MyApp.controller('ContactController', function ContactController ($scope, EmailService) {
$scope.formSubmit = function(form) {
EmailService.send(form).then(function(data) {
if(data.message.sent) {
$scope.resetForm();
alert("Message Sent");
}
else {
alert("Something went wrong. Try emailing me.");
}
});
}
$scope.resetForm = function() {
$scope.name = "";
$scope.email = "";
$scope.message = "";
}
});
MyApp.factory('AjaxService', function AjaxService ($q, $http) {
return {
http: function(ajaxParams) {
var deferred = $q.defer();
$http(ajaxParams)
.success(function (data, status, headers, config) {
deferred.resolve({
success: true,
status: status,
message: data
});
})
.error(function (data, status, headers, config) {
deferred.reject({
success: false,
status: status,
message: "Http Error"
});
});
return deferred.promise;
}
}
});
MyApp.factory('EmailService', function EmailService (AjaxService) {
return {
send: function(emailData) {
var ajaxParams = {
method: 'POST',
url: ''//where ever your form handler is,
data: {
name: emailData.name.$modelValue,
email: emailData.email.$modelValue,
message: emailData.message.$modelValue
},
cache: false
}
return AjaxService.http(ajaxParams);
}
}
});

Resources