Angular: check value ng-blur - javascript

I'm trying to build a form in Angular, but i'm new with it, so I need some help :)
I have a field 'email' which should be checked when the user leave that field. A function in my controller should to check the entered value if it already exist in the database (ajax/http).
I found the 'ng-blur' function and have created a function in my controller to check the email. But, the $scope.user.email is undefined, and I don't known what i'm doing wrong. Can somebody help me?
This is my code so far:
HTML (jade)
p.claim-text Email
abbr.required.claim-text(title='required') *
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', value='', name='email', ng-model='user.email', ng-blur='checkEmail()' required)
p(ng-show="registerForm.email.$invalid && !registerForm.email.$pristine").help-block Invalid emailadres
p(ng-show="emailExists").help-block User exists! Click here to login
Controller function
$scope.checkEmail = function(){
console.log($scope.user.email);
$http({
method: 'GET',
url: '[someurl]',
data: $scope.user.email,
}).then(function successCallback(response){
//if response is true, set emailExists to true;
}, function errorCallback(response){
});
}

Please try this snipped
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope','$http', function($scope, $http) {
//You can check POST at server side to get the entered email
$scope.checkEmail = function(email){
//REMOVE THIS LINE
console.log(email);return false;
$http({
method: 'POST',
url: '[someurl]',
data: email,
}).then(function successCallback(response){
//if response is true, set emailExists to true;
}, function errorCallback(response){
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!--HTML -->
<div ng-app="myApp" ng-controller="GreetingController">
<input type="text" ng-blur="checkEmail(email)" ng-model="email"/>
</div>
OR
<!--JADE -->
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', name='email', ng-model='user.email', ng-blur='checkEmail(user.email)' ng-init="user.email=''" required)

You can pass the email to checkEmail function
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', value='', name='email', ng-model='user.email', ng-blur='checkEmail()' required)
Then in controller you just need to get the email from argument
$scope.checkEmail = function(){
console.log($scope.user.email);
$http({
method: 'GET',
url: '[someurl]',
data: $scope.user.email,
}).then(function successCallback(response){
//if response is true, set emailExists to true;
}, function errorCallback(response){
});
}

Related

How to change location and refresh page in angular js

I have a function :
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
return response.data;
});
}
and the function work perfectly, but i want my page change to datalist and refresh datalist after insert() true. my function insert() run in the route "localhost/learn/#!/administrator" so i want it change to route "localhost/learn/#!/" after insert() true. i used location.href='#!/' but it not work for refresh datalist automaticaly, just change location.
If you want to update an object from a service call, you can do the following. I have added an onError function too, to help with debugging.
Tip: Research adding service calls into a Service that AngularJS framework provides. It helps for writing maintainable and structured code.
$scope.objectToUpdate;
$scope.insert = function(){
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
$http({
method: 'POST',
url: './sys/mac.php',
data : data
}).then(function(response){
$scope.objectToUpdate = response.data.d;
}, function(e){
alert(e); //catch error
});
}
Optional Service
Below is an example of how to make use of Angular Services to make server calls
app.service('dataService', function ($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function (url, data) {
// $http() returns a $promise that we can add handlers with .then() in controller
return $http({
method: 'POST',
url: './sys/' + url + '.php',
dataType: 'json',
data: data,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
};
});
Then call this service from your controller, or any controller that injects DataService
var data = {
'username' : $scope.username,
'password' : $scope.password,
'nama_lengkap' : $scope.nama_lengkap
}
dataService.getData('mac', data).then(function (e) {
$scope.objectToUpdate = e.data.d;
}, function (error) {
alert(error);
});

Angularjs response not printing in form

I am trying to print the response from my controller to my form. But it is not printing the messages passed from it.
Here is my controller .js file
app.controller('regCtrl', function ($scope) {
});
$scope.doRegister = function ()
{
username = $scope.signup.registerUserName;
email = $scope.signup.email;
password = $scope.signup.registerPassword;
$http({
url: 'app/toolkit/calls/doRegister.php',
method: "GET",
params: {username: username, email: email, password: password}
}).success(function (status, data, response, header) {
$scope.data.msg = 'Account not Activated'
});
};
and in the form i have
<div ng-controller="regCtrl">
<div ng-if="data.show" ng-bind="data.msg"></div>
What is the mistake i am doing and how can i make the response messages print in the form.
I fixed it by turning it the $scope.data true by
$scope.data = {show: true};
then it works.

POST form data using AngularJS

I'm trying to use AngularJS to POST a form to an API I'm developing.
The form has novalidate, name="addMatchForm", and ng-submit="submit(addMatchForm)". The addMatchForm is as followed:
app.controller('addMatchController', ['$scope', 'players', 'matches', function($scope, players, matches) {
...
$scope.submit = function(form) {
form.submitted = true;
// Make sure we don't submit the form if it's invalid
if ( form.$invalid ) return;
matches.add(form).success(function(data) {
console.log('post result:', data);
})
}
}]);
app.factory('matches', function($http) {
return {
add: function(data) {
return $http.post('/matches', data);
}
}
});
But the weird thing is that each and every input's value becomes an empty object at that point. This is the Form Data from Chrome Developer Tools:
{"a_score":{},"b_score":{},"day":{},"month":{},"year":{},"a_player1":{},"a_player2":{},"b_player1":{},"b_player2":{},"submitted":true}:
I did add the content-type part already.
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
Any ideas?
Try to use $http like this:
return $http({
method: 'POST',
url: '/matches',
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

Initialize $scope.model childs to "" or null

I'm doing this form and I'm sending the info through a $http request like this with angular
$http({
method:"POST",
url: "controllers/servicerequest.php",
data:
{
servicerequest: $scope.formData
},
headers: {'Content-Type': 'application/json'}
}).success(function(response, status, headers, config){
console.log(response);
if(response.success){
$window.open('reports/bol.php?bol='+response.id);
bootbox.alert('Service Request '+response.id+' has been processed.');
}
else{
bootbox.alert('Error message:' + response.message);
}
});
as you can see I'm sending all the data in the $scope.formData, the binding of the info works of this 2 ways
<div class="col-md-4">
<input type="text" class="form-control shipper" ng-model="formData.shipperdescripcion" name="shipper" id="shipper" ui-autocomplete="shipper">
<span class="help-block">
{{formData.shipperlocation}}
</span>
</div>
select: function(event, ui){
$scope.formData.trailerid = ui.item.id;
$scope.formData.trailerclave = ui.item.clave;
$scope.formData.trailerdueno = ui.item.propietario;
$scope.formData.trailer = ui.item.desc;
},
The thing is that I need to initialize all of the form data childs to "" when the controller loads otherwhise my the $scope.formData will be looking like this when I send the request
{}
for example, when I type something in the input the json changes from that, to this
{
"shipperdescripcion": "BUENAVENTURA AUTOPARTES S.A. DE C.V.",
}
but what I need is that before anything the controller loads the json of this way right from the start like this
{
"shipperdescripcion": "",
}
In your controller code, you can initialize the object, like the following:
$scope.model = {
shipperdescription: '', /* changing the spelling here to be correct */
id: '',
shipper: '',
shipperlocation: ''
}
A few thoughts: please consider using camelCase if possible to make your code more readable.

Get selected options and pass it using $http in Angularjs?

I am trying to pass the selected option value calling on the function on change.
<div class="col-md-4">
<select id="mkSelect" ng-model="formData.mk" name="mkSelect" ng-options="mk.MkIdLabel group by mk.FY for mk in mks" ng-change="update()" class="form-control">
</select>
</div>
And in the controller:
$scope.update = function() {
// this displays the MarketId value in the log
console.log($scope.formData.mk.MarketId);
$http({
method: 'POST',
url: 'getMailStatus.php',
// but while trying to send to "getMailStatus.php" it says its undefined
data: $.param($scope.formData.mk.MarketId),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
The console.log displays the selected id , but when I try to pass the same using $http it says undefined ($scope.formData.market.MarketID = undefined)
Can anybody point me what i am doing wrong?
$.param needs an object, not a simple value.
http://api.jquery.com/jquery.param/
Try with this:
data: $.param({mkId: $scope.formData.mk.MarketId}),

Categories

Resources