Initializing AngularJS controller member - angularjs

I'm trying to create an html/angularjs form that submits data to my webserver. The page is loading the controller because it does execute the submit function. I get an "ReferenceError: formData is not defined" error when I reference formData data. I thought this was the proper way to initialize members of a controller.
var app = angular.module('messagingForm', []);
app.controller('messagingController', function($scope, $http) {
$scope.formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(sendContact) {
$scope.submitted = true;
console.log('validating data');
if (sendContact.$valid) {
console.log('sending data');
$http({
method: 'post',
url: 'email.php',
data: {
'name': formData.userName,
'email': formData.email,
'subject': formData.subject,
'message': formData.message
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} //set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
});
} else {
console.log('validating not good');
alert('failed');
}
}
});
I'm unclear how I initialize a member variable I guess. what is the right way to do this?
Matt.

Try with this:
Change:
data: {
'name': formData.userName,
'email': formData.email,
'subject': formData.subject,
'message': formData.message
},
to
data: {
'name': $scope.formData.userName,
'email': $scope.formData.email,
'subject': $scope.formData.subject,
'message': $scope.formData.message
},
Then:
var app = angular.module('messagingForm', []);
app.controller('messagingController', function($scope, $http) {
$scope.formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(sendContact) {
$scope.submitted = true;
console.log('validating data');
if (sendContact.$valid) {
console.log('sending data');
$http({
method: 'post',
url: 'email.php',
data: {
'name': $scope.formData.userName,
'email': $scope.formData.email,
'subject': $scope.formData.subject,
'message': $scope.formData.message
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} //set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
});
} else {
console.log('validating not good');
alert('failed');
}
}
});
Because in your code, «formaData» it doesn't exist in the context. You might try also declaring a local variable, something like this:
var formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
Example:
var app = angular.module('messagingForm', []);
app.controller('messagingController', function ($scope, $http) {
var formData = {
userName: "bob",
email: "bob#bob.com",
subject: "why",
message: "why not?"
};
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(sendContact) {
$scope.submitted = true;
console.log('validating data');
if (sendContact.$valid) {
console.log('sending data');
$http({
method : 'post',
url : 'email.php',
data : {
'name': formData.userName,
'email': formData.email,
'subject': formData.subject,
'message': formData.message
},
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
});
} else {
console.log('validating not good');
alert('failed');
}
}
});

You could also create the formData object as a constant and then explicitly pass it in to the controller.
var app = angular.module('messagingForm', []).constant("formData", {
'userName': 'bob',
'email': 'bob#bob.com',
'subject': 'why',
'message': 'why not?'
});
app.controller('messagingController', function($scope, $http, formData) {
Rest of you code here...
It just makes it a little clearer and easier to test.

Related

ngResource return success callback result by service

I have recetly began an adventure with AngularJs but idea of promises and returning asynchonous data overhelmed me.
I am trying to accomplish simple data returining via .factory method and $resource service.
Here is my $resource service returning promise
(function () {
angular.module('token')
.factory('tokenService', ['$resource', 'baseUri', tokenService]);
function tokenService($resource, baseUri) {
return $resource(baseUri + 'token', {}, {
post: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
});
}
})();
I am using this service in another service which should returns data.
(function () {
angular.module('authorization')
.factory('authorizationService', ['$httpParamSerializer', 'tokenService', authorizationService]);
function authorizationService($httpParamSerializer, tokenService) {
return {
authorization: function(user){
var token = {};
tokenService.post({}, $httpParamSerializer({
grant_type: 'password',
username: user.login,
password: user.password,
client_id: user.clientId
}), function(response){
token = response;
console.log('authorizationResponse', response);
console.log('authorizationToken', token);
});
// .$promise.then(function(response){
// token = response;
// console.log('authorizationResponse', response);
// console.log('authorizationToken', token);
// });
console.log('finalToken', token);
return token;
}
};
}
})();
But i cannot force token variable to posses tokenService.post() result before returing.
First: inject $q in your authorizationService.
Try this:
authorization: function(user) {
return $q(function(resolve, reject) {
tokenService.post({}, {
grant_type: 'password',
username: user.login,
password: user.password,
client_id: user.clientId
})
.$promise
.then(function(token) {
resolve(token);
})
.catch(function(err) {
reject(err);
});
});
}
Then, in your controller, you can use:
authorizationService.authorization(user)
.then(function(token) {
// Some code here
})
.catch(function(err) {
// Handle error here
});

res.json sending old data

Hi I have an issue that I can't really explain with res.json from express.
Here is my /login route:
router.post('/login', function (req, res) {
if (req.body.user) {
var newUser = (typeof req.body.user === 'string') ? JSON.parse(req.body.user) : req.body.user;
User.findOne({ email: newUser.email })
.exec(function (err, user) {
if (err) {
return res.json({ error: true, data: err });
} else {
if (user !== undefined && user !== null) {
// Check password and generate a token if it exist
encrypt.checkHash(newUser.pwd, user.pwd, function (err, isCorrect) {
if (err) {
return res.json({ error: true, data: err });
} else {
if (isCorrect != false) {
// Generate token and send it
Token.generateToken({
_id: user._id, email: user.email,
iat: moment().valueOf(),
exp: moment().add(30, 'minutes').valueOf(),
},
conf.secret,
{},
function (err, token) {
if (err) {
return res.json({ error: true, authenticate: false, data: err });
} else {
console.log('Logged');
return res.json({
error: false,
token: token,
authenticate: true,
msg: 'user_connected',
});
}
});
} else {
console.log('Not logged');
return res.json({ error: true, authenticate: false, msg: 'user_undefined' });
}
}
});
} else {
return res.json({ error: true, authenticate: false, msg: 'user_undefined' });
}
}
});
} else {
return res.json({ error: true, authenticate: false, msg: 'user_empty' });
}
});
And here the function where I made my request to that route:
userRequest.auth = function (user) {
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
And here my onClick function which start the process
var promise = userRequest.auth($scope.user);
promise.then(function (response) {
var data = response.data;
$log.info('Login RESPONSE ', response);
if (data.error == false && data.authenticate == true) {
$log.info('You are logged');
$scope.notification = setAlertBoxOptions($scope.notification, true, 'alert-success', 'Vous êtes maintenant connecté');
} else {
$log.info('Wrong informations');
$scope.notification = setAlertBoxOptions($scope.notification, true, 'alert-danger', 'Utilisateur inconnue');
}
}, function (reason) {
$log.error(reason);
});
My function's encrypt.checkHash callback work and the value isCorrect is the good one when checking my password hash. It log 'Logged' if the password is correct and 'Not logged' if it's not.
The first time I made a request on this route it send me back an response by res.json and I get the expected data.
But after the first request, the data I receive is always the one I received on the first query.
e.g: The first time I send correct identification info and it return me
{error: false, token: token, authenticate: true, msg: 'user_connected'}
but after that, every time I try to make another query on that route I keep receiving this JSON object event if my identification info are false.
I'm not an expert in Nodejs and I tried to replace all my
res.json({...})
by
return res.json({...})
to stop the execution but the result still the same.
Can you share your wisdom with me and help me solve this case please ?
I found out why it was happening, in my angularJS factory I initialize only once the $q service and where using it inside a method of the factory. like this:
angular.module('myApp').factory(
'userRequest',
['$log', '$q',
function ($log, $q) {
// Initialized wrongly
var deferred = $q.defer();
userRequest.auth = function (user) {
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
}])
instead of:
angular.module('myApp').factory(
'userRequest',
['$log', '$q',
function ($log, $q) {
userRequest.auth = function (user) {
// Where to initialize it
var deferred = $q.defer();
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
}])

Add post/comment angular js in WP Rest Api

I have a problem with posting data to the WP Rest API in combination with my Angular webApp. My first guess is that I am not posting the data in the right format.
My function to post the data is as follows: (some data is static for test purposes only)
$scope.submitComment = function () {
var d = new Date();
commentForm = [
{
'author_email': $scope.email,
'author_name': $scope.name,
'author_url': 'http://www.domain.com',
'content': $scope.comment,
'date': '2015-11-29T20:10:36',
'date_gmt': '2015-11-29T19:10:36',
'karma': '',
'parent': 0,
'post': $scope.postID,
'status': 'approved',
'type': 'comment'
}
];
$http({
method: 'POST',
url: 'http://www.domain.com/wp-json/wp/v2/comments?post=' + $scope.postID,
data: commentForm
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
});
$scope.showCommentForm = false;
$scope.showCommentButton = true;
};
When I log commentForm, all the properties are set. But none of them are inserted into the database. What am I doing wrong? The response of the $http Post is a 201, so it seems successful.

Angularjs Resource Object a.push is not a function

I have created a resource object:
factory('TextResource',
function($resource) {
return $resource(adminBaseUrl+'/texts/:type', {}, {
create: {method: 'POST', params: {type:'create'}, headers: {'Content-Type':'application/x-www-form-urlencoded'}},
update: {method: 'POST', params: {type:'update'}, headers: {'Content-Type':'application/x-www-form-urlencoded'}},
query: {method: 'GET', params: {type: 'list'}},
remove: {method: 'POST', params: {type: 'remove'}, headers: {'Content-Type':'application/x-www-form-urlencoded'}},
getText: {method: 'GET', params: {type: 'get', id:'#id'}}
});
}
)
And my controller is:
controller('EditText', ['$scope', '$location', '$routeParams', 'TextResource', 'HttpStatusMessage',
function($scope, $location, $routeParams, TextResource, HttpStatusMessage) {
$scope.alerts = [];
$scope.languages = [];
TextResource.getText(
{id: $routeParams.id},
function(data) {
$scope.languages = data.result;
},
function(error) {
var httpError = new HttpStatusMessage(error.status);
$scope.alerts.push({type:'error', msg:httpError.msg});
});
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
}
$scope.submit = function() {
TextResource.update(
$scope.languages,
function(data) {
if( data.type == 'success' ) {
$location.path('texts');
} else {
$scope.alerts.push({type:data.type, msg:data.message});
}
},
function(error) {
var httpError = new HttpStatusMessage(error.status);
$scope.alerts.push({type:'error', msg:httpError.msg});
});
}
$scope.cancel = function() {
$location.path('texts');
}
}
])
The response i am getting from TextResource.getText request is:
{"result":[{"id":"3","value":"This is my first text<br>","key":"my_first_text","language_id":"1","name":"English"},{"id":"3","value":"Ceci est mon premier texte","key":"my_first_text","language_id":"3","name":"French"}],"num_rows":2}
Now when i click on submit it displays the error:
Error: a.push is not a function
The response object contains 2 keys result and num_rows result is an array. The reason i am not using isArray parameter in resource object is in case if any error occured in server like session time out, access not allowed etc. the server returned a object contains error msg.
Problem is solved by modifying the update function like:
$scope.submit = function() {
TextResource.update(
{'language':$scope.languages},
function(data) {
if( data.type == 'success' ) {
$location.path('texts');
} else {
$scope.alerts.push({type:data.type, msg:data.message});
}
},
function(error) {
var httpError = new HttpStatusMessage(error.status);
$scope.alerts.push({type:'error', msg:httpError.msg});
});
}
I was directly posting an array in update which throws the error. So encapsulating in another key solved the problem.

Creating a user session with AngularJS and DreamFactory

I'm trying to make a simple login function for my AngularJS application. I'm using Dream Factory for my backend server database and I can't seem to be able to create a session from my login-function.
This is the factory I have set up:
dfdevApp.factory('SessionService', function($resource, $q) {
var sessionResource = $resource('https://dsp-myusername.cloud.dreamfactory.com/rest/user/session', {},
{ update: { method: 'PUT' }, query: {method: 'GET', isArray: false} });
return {
create: function (user) {
var deferred = $q.defer();
sessionResource.save(user, function (result) {
deferred.resolve(result);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
}
});
And this is the code from my controller:
// $scope.ting = Liste.get()
$scope.user = {'email' : '', 'password': ''};
$scope.login = function() {
console.log(JSON.stringify($scope.user));
$scope.user = SessionService.create(JSON.stringify($scope.user), function(success) {
$rootScope.loggedIn = true;
$location.path('/');
}, function(error) {
$scope.loginError = true;
});
};
});
I get a 400 every time I try to post.
Your post should be like this one:
{"email":"you#youremail.com","password":"yourpassword"}
Also don't forget to include your app_name in the URL or as a header (in this case, call it X-DreamFactory-Application-Name).
You can find more info here:
http://blog.dreamfactory.com/blog/bid/326379/Getting-Started-with-the-DreamFactory-API
I also built an "SDK" which handles all this for you.
https://github.com/dreamfactorysoftware/javascript-sdk

Resources