Accessing Form elements and div from Angular Promise - javascript

I am learning angular js. I just want to clear the form fields and show a success div inside a http then().
this.formSubmitted = false;
this.successs = false;
myResumeApp.controller("FormController",['$http', function($http){
this.formSubmit = function(contactForm) {
this.formSubmitted = true;
if(contactForm.$valid)
{
$http({
method: 'post',
url: 'http://jerrythimothy.is-great.net/mailme.php',
data: $.param({
fname : this.fname,
email : this.email,
content : this.content
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
this.successs = true;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});// JavaScript Document
}
};
}]);
<div class="container" ng-controller="FormController as formCtrl">
<h2>Contact me</h2>
<div ng-show="formCtrl.successs" class="alert alert-success fade in" style="padding-top:5px;padding-bottom:5px;margin-top:5px;margin-bottom:5px;">Thank you for contacting me. I will be in touch with you shortly.</div>
<form role="form" name="contactForm" novalidate ng-submit="formCtrl.formSubmit(contactForm)">
Please let me know whether there is anything wrong with my code or any other suggestions. The control is coming inside the then() block. But I need to know how to access the successs element and clear the form fields.
Thank you.

Instead of this, use $scope (and add it to dependencies). Right know your successs property is assigned to different objects (window and callback function).
Controller code:
myResumeApp.controller("FormController",[
'$scope',
'$http',
function($scope, $http){
$scope.successs = false;
$scope.formSubmitted = false;
$scope.msg = {};
$scope.formSubmit = function(contactForm) {
$scope.formSubmitted = true;
if(contactForm.$valid)
{
$http({
method: 'post',
url: 'http://jerrythimothy.is-great.net/mailme.php',
data: $.param({
fname : $scope.msg.fname,
email : $scope.msg.email,
content : $scope.msg.content
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
$scope.successs = true;
$scope.msg = {};
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});// JavaScript Document
}
};
}
]);
HTML code:
<div class="container" ng-controller="FormController as formCtrl">
<h2>Contact me</h2>
<div ng-show="successs"
class="alert alert-success fade in"
style="padding-top:5px;padding-bottom:5px;margin-top:5px;margin-bottom:5px;">
Thank you for contacting me. I will be in touch with you shortly.
</div>
<form role="form" name="contactForm" novalidate ng-submit="formSubmit(contactForm)">
<input type="text" name="name" ng-model="msg.fname" />
<input type="text" name="email" ng-model="msg.email" />
<input type="text" name="content" ng-model="msg.content" />
<input type="submit" value="submit" />
</form>

You should be able to handle that in successCallback.
... .then(function successCallback(response) {
this.successs = true;
contactForm.reset()
}, ...
Also I don't think that this inside successCallback is same as in line where you initialize this.formSubmitted = false;...

Related

ng-model is not working with ng-value in AngularJS

Below is my View page
<form name="form">
<label>Name</label>
<input name="name" type="text" ng-model='user.name' ng-value='emp.name' required />
<span ng-show="form.name.$touched && form.name.$invalid">Name is required</span>
<button ng-disabled="form.name.$touched && form.name.$invalid" ng-click='formUpdate()'>Update</button>
</form>
This is my controller
$scope.formUpdate = function() {
$scope.status = false;
$http({
method : 'POST',
url : 'model/update.php',
data : $scope.user ,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function mySuccess(response) {
$scope.update = response.data;
console.log(response.data);
}, function myError(response) {
$scope.update = response.statusText;
});
};
When I am using data: $scope.user in my HTTP call I am getting blank values on console but if I used data: $scope.emp, then I never get updated values of input fields rather getting old values of input fields.
ng-value binds the given expression to the value of the element.
As I understand your question, you are trying to initialize the input value to emp.name.
You should change your input to:
<input type="text" ng-model='user.name' ng-init='user.name = emp.name' required />
ng-init docs
try this code;
$scope.formUpdate = function(){
$scope.status = false;
$scope.$applyAsync();
$http({
method : 'POST',
url : 'model/update.php',
data : $scope.user ,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function mySuccess(response) {
$scope.update = response.data;
$scope.$applyAsync();
console.log(response.data);
}, function myError(response) {
$scope.update = response.statusText;
$scope.$applyAsync();
});
};

failed bind angularJS variable to nodejs

i have a problem sending my angularJS POST parameters to my nodejs server... i've seen many topics related to this, tried everything here and nothing works (there were more):
How to pass parameter in Angularjs $http.post
Angular: how to pass $scope variables into the Node.js server.
How to pass client-side parameters to the server-side in Angular/Node.js/Express
How to pass data from AngularJS frontend to Nodejs backend?
my relevant code that is envolved in this problem,
handlebars-template:
<div ng-controller='questions'>
<form method="POST" class="form-inline" class="my-search-menu">
<button ng-click="search()" class="btn btn-default glyphicon glyphicon-search" type="submit" style="background-color: #85C1E9;"></button>
<input style="direction: rtl" type="text" name="search_text" ng-model="search_text" class="form-control" placeholder="Search" aria-describedby="sizing-addon3">
</form>
</div>
AngularJS:
var myapp= angular.module('myapp', []);
myapp.controller("questions", function($scope,$http) {
$scope.search = function () {
var formdata = {search_text : $scope.search_text};
$http.post('/search', {params: formdata})
.success(function (data, status, headers, config) {
$scope.questions = data;
})
.error(function(data, status, header, config){
$scope.onerror = "Data: " + status;
});
console.log(formdata);
};
});
NodeJS:
app.post('/search', function (req,res,next){
var search_text = req.query.params.formdata.search_text;
console.log(req);
Question.find({$text: {$search: search_text}}).exec(function (err, questions){
res.json(questions);
});
});
There are few points you are missing. First in the anguar controller
$http.post('/search', {params: formdata})
will send {params:formdata} as request body in the node server.. So in the server end you will receive the data as request.body. correct way to receive the body in this case will be ..
app.post('/search', function (req,res,next){
var search_text = req.body.params.search_text;
//TODO
});
If you want to send the data as parameter then in controller write the function like this...
$http({
method: 'POST',
url: '/search/'+paramData,
}).then(function successCallback(response) {
//TODO
}, function errorCallback(error) {
//TODO
});
And in the server side...
app.post('/search/:searchText', function (req,res,next){
var paramData = req.params.searchText;
//TODO
});

Angular: check value ng-blur

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){
});
}

Populate textfield on page opening

I have simple form being opened clicking on tab
<form name="instructions" class="form form-horizontal" ng-controller="InstructionsPage">
<div class="form-group">
<label for="instruction">Instructions</label>
<textarea id="instruction" rows="5" class="form-control" ng-model="instructions">
</textarea>
</div>
<button class="btn btn-primary" data-ng-click="saveInstructions()">Save</button>
</form>
and related controller
angular.module('myApp.controllers')
.controller('InstructionsPage', ['$scope', function ($scope) {
use strict';
$scope.saveInstructions = function() {
var data = $scope.instructions;
// post request with data from textfield inside
}
}]);
How to receive data with GET-request to populate textfield with default/previously saved data? Thank you!
You can just update your $scope.instructions variable which is bound to the <textarea> ng-model from your controller like this:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.instructions = response;
}, function errorCallback(response) {
});

angular js: Error: $ is not defined in http post

I'm trying to post values from a form. Form has two fields- name and email. I have setup the controller as well but when i try to post, error is shown.
<form name="save" ng-submit="sap.saved(save.$valid)" novalidate>
<div class="form-group" >
<input type="text" name="name" id="name" ng-model="sap.name" />
</div>
<div class="form-group" >
<input type="email" name="email" id="email" ng-model="sap.email" />
</div>
<div class="form-actions">
<button type="submit" ng-disabled="save.$invalid || sap.dataLoading">Save</button>
</div>
</form>
My controller is:
(function() {
angular
.module('myApp.saved', [])
.controller('dataController', function($scope, $http) {
var sap = this;
$scope.post = {};
$scope.post.login = [];
$scope.sap = {};
$scope.index = '';
var url = 'save.php';
sap.saved = function(isValid)
{
if (isValid)
{
$http({
method: 'post',
url: url,
data: $.param({'user' : $scope.sap }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response)
{
// success
alert('success');
},
function(response)
{
// failed
alert('failed');
});
}
};
});
})();
When i submit, $ is not defined is shown. I'm pretty much new in angular. Can anyone tell what all mistakes I made?
$ is alias for jQuery and param is a jquery method.
Have you included jQuery?
data: $.param({'user' : $scope.sap }),
should be
data: {
'user': $scope.sap //POST parameters
}
data – {string|Object} – The response body transformed with the transform functions

Categories

Resources