angular resource passing unwanted parameters - javascript

I am trying to setup a server side authentication service using rails like this :
Javascript:
angular.module('myApp',['ngResource'])
.factory("Session",['$resource',function($resource){
return $resource('/sessions',{}, {
create: {method: 'POST', isArray: false},
destroy: {method:'DELETE', url: '/sessions/destroy.json' }
});
}])
.controller("LoginController",['$scope','Session',function($scope,Session){
$scope.model = {};
$scope.login = function(username,password){
//Session.save({username: username, password: password}).then(function(success){
// $scope.model.user = success.data;
// console.log("New Session");
//},function(error){
// console.log("Login failed!!!");
// console.log(error);
//});
$scope.model.user = {
first: "John",
last: 'Doe'
};
};
$scope.logout = function(){
Session.destroy().then(function(success){
$scope.model.user = {};
console.log("Session Deleted!!!");
},function(error){
console.log("Error in Session delete...");
console.log(error);
})
};
}]);
html:
<div class="navbar navbar-inverse" role="navigation" ng-controller="LoginController">
<div class="navbar-right navbar-form " style="color:white" ng-show="model.user">
<span class="glyphicon glyphicon-user"></span>
<span>{{ model.user.first + ' ' + model.user.last}}</span>
<button ng-click="logout()" type="submit" class="btn btn-danger navbar-btn">Logout</button>
</div>
<div class="navbar-form navbar-right" role="login" ng-hide="model.user">
<div class="form-group">
<a ng-href="#">new user? </a>
<a ng-href="#"> forgot password?</a>
</div>
<form class="form-group" name="loginForm" ng-submit="login()">
<input type="text" class="form-control" placeholder="username" ng-model="username" />
<input type="password" class="form-control" placeholder="password" ng-model="password" />
<button type="submit" class="btn btn-primary navbar-btn">Login</button>
</form>
</div>
</div>
But when I make a logout request, angular is putting a extra parameter see rails server log:
Started DELETE "/sessions/destroy.json" for 127.0.0.1 at 2014-04-26 18:30:30 -0400
Processing by SessionsController#destroy as JSON
Parameters: {"id"=>"destroy"}
Why is this happening ?

try this:
angular.module('myApp',['ngResource'])
.factory("Session",['$resource',function($resource){
return $resource('/sessions/:action',{}, {
create: {method: 'POST', isArray: false},
destroy: {method:'DELETE', params: { action: 'destroy.json' } }
});
}])

Related

how to save json array in mongodb using nodejs

i tried creating a new mongodb document using nodejs here is my schema
var resumeSchema = mongoose.Schema(
{
user:{type: mongoose.Schema.Types.ObjectId, ref: 'User'},
education:[
{
name:{type: String, required: true},
qualification:{type: String, required: true},
startEnd:{type: String, required: true},
note:{type: String, required: true}
}
],
experience:[
{
employer:{type: String, required: true},
jobTitle:{type: String, required: true},
startEnd:{type: String, required: true},
note:{type: String, required: true}
}
]
}
)
var Resume = mongoose.model('Resume', resumeSchema);
here is my nodejs route
router.post('/add-resume', function(req, res, next) {
var newResume = new Resume();
newResume.user = req.user._id;
newResume.education= req.body.educations;
newResume.experience = req.body.experiences;
newResume.save(function(err, resume){
if (err) {
return next(err);
}else{
console.log(resume);
}
});
});
});
Where req.body.educations and req.body.experiences are json array.
please i need help on how to fix this
am using angular js on the client side and the data am sending to the server is a formData. here is my client code
angular
.module('app')
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
angular
.module('app')
.controller('addresumeCtrl', addresumeCtrl);
function addresumeCtrl ($scope,ngDialog,$http) {
$scope.resume = {};
$scope.educations = [];
$scope.experiences = [];
$scope.resume.educations = $scope.educations;
$scope.resume.experiences = $scope.experiences;
$scope.addNewEducation = function() {
$scope.educations.push({});
};
$scope.addNewExperience = function() {
$scope.experiences.push({});
};
$scope.removeEducation = function(index) {
$scope.educations.splice(index, 1);
};
$scope.removeExperience = function(index) {
$scope.experiences.splice(index, 1);
};
$scope.create = function(){
var uploadUrl = "/user/add-resume";
var fd = new FormData();
for(var key in $scope.resume)
fd.append(key, $scope.resume[key]);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function (response) {
}, function (error) {
});
};
}
and here is the html
<form>
<!-- Education -->
<div class="form with-line">
<h5>Education <span>(optional)</span></h5>
<div class="form-inside">
<!-- Add Education -->
<div data-ng-repeat="education in educations" class="form boxed education-box">
<i class="fa fa-close"></i>
<input class="search-field" type="text" placeholder="School Name" ng-model="education.name"/>
<input class="search-field" type="text" placeholder="Qualification(s)" ng-model="education.qualification"/>
<input class="search-field" type="text" placeholder="Start - end date eg 2000 - 2010" ng-model="education.startEnd"/>
<textarea name="desc" id="desc" cols="30" rows="10" placeholder="Notes (optional)" ng-model="education.note" ></textarea>
</div>
<i class="fa fa-plus-circle"></i> Add Education
</div>
</div>
<!-- Experience -->
<div class="form with-line">
<h5>Experience <span>(optional)</span></h5>
<div class="form-inside">
<!-- Add Experience -->
<div data-ng-repeat="experience in experiences" class="form boxed experience-box">
<i class="fa fa-close"></i>
<input class="search-field" type="text" placeholder="Employer" ng-model="experience.employer"/>
<input class="search-field" type="text" placeholder="Job Title" ng-model="experience.jobTitle"/>
<input class="search-field" type="text" placeholder="Start / end date eg 2000 - 2010" ng-model="experience.startEnd"/>
<textarea name="desc1" id="desc1" cols="30" rows="10" placeholder="Notes (optional)" ng-model="experience.note"></textarea>
</div>
<i class="fa fa-plus-circle"></i> Add Experience
</div>
</div>
<div class="divider margin-top-0 padding-reset"></div>
Preview <i class="fa fa-arrow-circle-right"></i>
</form>

Using Angular to post to a APi

First week using Angular and I am now trying to post to a third party API.
I would like some help getting this form posting the data correctly, for extra points some comments and expectation on what line is doing what.
I am getting this error
ReferenceError: formData is not defined
at h.$scope.processForm (controller.js:116)
at angular.js:10567
at angular.js:18627
at h.$eval (angular.js:12412)
at h.$apply (angular.js:12510)
at HTMLFormElement.<anonymous> (angular.js:18626)
at angular.js:2780
at q (angular.js:330)
at HTMLFormElement.c (angular.js:2779)
The API I am posting to requires user_key 0000 and api_key 0000to be sent, although theses are not dynamic like the form fields so are always the same.
My current form
<form name="myForm" id="signup-form" class="col-sm-8 col-sm-offset-2" ng-click="postdata(Fname, Lname, email)">
<div class="form-group">
<label for="first-name">First Name*</label>
<input type="text" class="form-control col-sm-12" name="Fname" placeholder="Enter first name"
ng-model="formData.Fname"
ng-required="true">
<span ng-if="!myForm.Fname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Last Name*</label>
<input type="text" class="form-control col-sm-12" name="Lname" placeholder="Enter last name"
ng-model="formData.Lname"
ng-required="true">
<span ng-if="!myForm.Lname.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group">
<label for="first-name">Email*</label>
<input type="email" class="form-control col-sm-12" name="email" placeholder="Enter valid E-mail"
ng-model="formData.email"
ng-required="true">
<span ng-if="!myForm.email.$invalid" class="glyphicon glyphicon-ok " style="color: green" aria-hidden="true"></span>
</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-3">
<button ui-sref="form.select" class="btn btn-block btn-info"
ng-disabled="!myForm.$valid">
Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
</button>
</div>
</div>
</form>
My controller
// submit button controller POST
// =============================================================================
.controller('formController', function ($scope, $http) {
$scope.Fname = null;
$scope.Lname = null;
$scope.email = null;
$scope.lblMsg = null;
$scope.processForm = function (Fname, Lname, email) {
var data = {
Fname: formData.Fname,
Lname: formData.Lname,
email: formData.email,
api_key: 0000,
user_key: 0000
};
//Call the services
$http.post('https://API/do/create', JSON.stringify(data)).then(function (response) {
if (response.data)
$scope.msg = "Post Data Submitted Successfully!";
}, function (response) {
$scope.msg = "Service not Exists";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
You should have some changes in your code.
1- Declare $scope.formData = {}
2- Remove
$scope.Fname = null;
$scope.Lname = null;
$scope.email = null;
$scope.lblMsg = null;
because you can access to them with $scope.formData object.
3- change formData.Fname to $scope.formData.Fname, and other similar to this
$scope.formData = {}; // declare in controller
var data = {
Fname: $scope.formData.Fname,
Lname: $scope.formData.Lname,
email: $scope.formData.email,
api_key: 0000,
user_key: 0000
};
4- you can pass formData object to function or don't pass it.If passing formData to function so use following
ng-click="postdata(formData)"
var data = {
Fname: formData.Fname,
Lname: formData.Lname,
email: formData.email,

replace angular app with another via $http

I am using Angular to try to replace my login form with a registration form when a user clicks "Sign up," but I can't seem to get the second form to interact with angular, since the controller loads before the second form.
As of right now, I'm using JQuery's html() function to replace the form, and if I were just using Jquery as a function, I'd just do the following:
$(window).on('click','submit',function(){
//function here
});
but I can't seem to get anything similar to work in Angular.
Original Form:
<div ng-app="login" ng-controller="loginCtrl">
<div id="formContainer">
<form ng-submit="loginSubmit()" id="loginForm" name="loginForm">
email: <input id="email" name="email" ng-model="email">
password: <input id="pw" name="pw" ng-model="pw">
<div class="row center">
<span ng-click="signup()" id="signupButton" class="button">Sign Up</span>
<span ng-click="login()" id="loginButton" class="button">Submit</span>
</div>
</form>
</div>
</div>
Registration Form:
<div ng-app="signup" ng-controller="signupCtrl" class="flexRow">
<form ng-submit="signupSubmit()" id="signupForm" name="signupForm">
email: <input name="signupEmail" ng-model="signupEmail" type="email">
password: <input name="signupPw" ng-model="signupPw">
first name: <input name="signupFirstName" ng-model="signupFirstName">
last name: <input name="signupLastName" ng-model="signupLastName">
<div>
<span ng-click="register()" id="register" class="button">Register</span>
</div>
</form>
</div>
Controller:
app.controller("loginCtrl",function($scope, $http){
//sign up
$scope.signup = function(){
$http({
method: "POST",
url: "/functions/signup",
data: {/* data in here */},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(
function successCallback(response){
$('#formContainer').html((response.data));
}, function errorCallback(response){
alert('error: \n'+ response.data);
}
);
}
//registration
$scope.register = function(){
$http({
method: "POST",
url: "/functions/register",
data: {/*data here */},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(
function successCallback(response){
$('#auth').html(response.data);
}, function errorCallback(response){
$('#auth').html('ERROR: ' + response.data);
}
);
}
});
Is there any way I can have the controller read the ng-click event on the dynamically added content?
Rule #1: Don't mix jQuery with Angular, especially in controllers.
You're breaking the Angular data binding by replacing the form contents with jQuery. Probably the easiest way to do what you are wanting to do is to have certain fields visible for existing users (username/password, and login button) and the other fields (for creating an account) visible when the signup button is clicked. This can be accomplished via a simple ng-show, and you don't need a second app for it (like you have listed in your example.)
<div ng-app="login" ng-controller="loginCtrl">
<div id="formContainer">
<form ng-show="!register" id="loginForm" name="loginForm">
email: <input id="email" name="email" ng-model="email">
password: <input id="pw" name="pw" ng-model="pw">
<div class="row center">
<span ng-click="signup()" id="signupButton" class="button">Sign Up</span>
<span ng-click="login()" id="loginButton" class="button">Submit</span>
</div>
</form>
<form id="signupForm" name="signupForm">
email: <input name="signupEmail" ng-model="signupEmail" type="email">
password: <input name="signupPw" ng-model="signupPw">
first name: <input name="signupFirstName" ng-model="signupFirstName">
last name: <input name="signupLastName" ng-model="signupLastName">
<div>
<span ng-click="register()" id="register" class="button">Register</span>
</div>
</form>
</div>
</div>
And the controller...
app.controller("loginCtrl",function($scope, $http){
$scope.register = false;
$scope.signup = function(){
$scope.register = !$scope.register;
};
//sign up
$scope.login= function(){
$http({
method: "POST",
url: "/functions/login",
data: {/* data in here */},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(
function successCallback(response){
//do something after success, like maybe redirect to a new page
}, function errorCallback(response){
alert('error: \n'+ response.data);
}
);
}
//registration
$scope.register = function(){
$http({
method: "POST",
url: "/functions/register",
data: {/*data here */},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(
function successCallback(response){
//do something after success, like maybe redirect to a new page
}, function errorCallback(response){
alert('error: \n'+ response.data);
}
);
}
});

How to load data in ngDialog

I have a requirement where I need to open a dialog from a jsp page and while opening the dialog, I need to load it with some prepopulated data from the server (using an AJAX call). If I make the AJAX call before opening the dialog, I get the data but the dialog loads like a new page. If I try to get the data in the new controller, the dialog still does not reflect the data. What should I use to make sure the dialog reflects the data that I am getting from the server
<div class="container-fluid" ng-controller="EditUserController">
<div class="text-center container-fluid">
<label class="sub-header">Edit User: {{userEmail}}</label>
</div>
<form action="editUser" method="post" name="editForm">
<div>
<div class="pull-right">
<label>Delete User</label><br> <a href="#"
class="btn btn-block btn-sm btn-danger" ng-click="deleteUser(userEmail)">{{userEmail}}</a>
</div>
<div>
<label>Change Role</label>
</div>
<div>
<label>
<input type="checkbox" ng-model="superVisor" name="superVisorFlag"
ng-true-value="1" ng-false-value="0" value="${existingUser.superVisorFlag}">
Make a Supervisor</label>
</div>
<div>
<input type="text" class="form-control" ng-model="email"
name="emailAddress" ng-disabled = "true"
ng-options="email for email in userEmail"
value="${existingUser.emailAddress}"
placeholder="Enter New User Email Address" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="firstName"
name="firstName" value="${existingUser.firstName}"
placeholder="Enter First Name" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="lastName"
name="lastName" value="${existingUser.lastName}"
placeholder="Enter Last Name" bs-typeahead>
</div>
<div>
Save Changes
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="<c:url value="/resources/scripts/admin.js"/>"></script>
The above is a jsp for the dialog. Below is my js file -
var app = angular.module('scc-admin', [ 'ngDialog', 'mgcrea.ngStrap' ]);
app.factory("UserList", function() {
var UserList = {};
UserList.data = [ {
userId : 111,
userFirstName : "xxx",
userLastName : "yyy",
userEmail : "xxx.yyy#zzz.com",
userRole : "Admin"
}, {
userId : 222,
userFirstName : "second",
userLastName : "last",
userEmail : "second.last#zzz.com",
userRole : "Manager"
}];
return UserList;
});
app.controller('UserSettingsController', function($scope, ngDialog, UserList,$http) {
// variable for the bashboard list
$scope.userList = UserList;
$scope.editUser = function(userEmail) {
$scope.userEmail = userEmail;
ngDialog.open({
template : 'editUser' ,
className : 'ngdialog-theme-default',
controller : 'EditUserController',
closeByEscape : true,
scope : $scope
});
};
$scope.addUser = function() {
ngDialog.open({
template : 'addUser',
className : 'ngdialog-theme-default',
controller : 'AddUserController',
closeByEscape : true,
scope : $scope
});
};
});
app.controller('EditUserController', function($scope, ngDialog, $http) {
ngDialog.template = $scope.output;
ngDialog.$modelValue = $scope.output;
var responsePromise = $http.get("initUser?email=" + $scope.userEmail);
responsePromise.success(function(data, status, headers, config) {
$scope.output = data;
console.log(data);
});
console.log($scope);
$scope.deleteUser = function(){
$scope.cfdump = "";
var str = {emailAddress : $scope.userForm.emailAddress.$modelValue};
str = JSON.stringify(str);
var request = $http({
method: 'post',
url: "deleteUser?formData=" + str,
data: ({formData:str})
});
request.success(function(html){
alert("success");
});
request.error(function(errmsg){
alert("Unable to delete user");
});
}
});
I am opening a dialog in usersettings controller and trying to load it with default data. I tried setting the new dialog's template to the output of the AJAX call, it did not work. What am I missing here?
After consulting the documentation, I learned following solution. It should work for you like it did for me.
To pass data (JSON Object) for ng-model inside the ngDialog, you can declare your ngDialog as following.
ngDialog.open({
template: 'my-template.html',
className: 'ngdialog-theme-plain',
data: $scope.myJSONObject
});
Now, with the above part done, you need to bind the data in your popup ngDialog, so go and put ngDialogData.myJSONObjectFieldName in your ng-model.
Consider following example for further elaboration. We assume that we have myJSONObject as following.
myJSONObject={
first_name: 'John',
last_name: 'Doe'
};
To use first_name inside your ngDialog's ng-model, simply put ng-model="ngDialogData.first_name".
To check whether the controller(VM) data is received in Modal Dialog use this
<pre>{{vm|json}}</pre>
Module and Controller:
var app = angular.module("DemoApp",['ngDialog']);
app.controller("DemoController",["$rootScope","ngDialog","productService",function($rootScope,ngDialog,productService){
var vm=this;
$rootScope.ngDialog = ngDialog; // to close Dialog using "ngDialog.close();" in ProductDialog.html
/* vm.products=[{brand:"Apple", price:60000, os:"iOS"},
{brand:"Samsung", price:35000, os:"Android"},
{brand:"Microsoft Lumia", price:30000, os:"Windows 10"}
];
*/
vm.getProductDetails=function() {
productService.getData().then(function (response) {
if (response.data) {
vm.products=response.data;
vm.ProdDialog();
}
});
};
vm.productPopup = function(x){
ngDialog.open({
template: 'ProductDialog.html',
className:'ProductDetailsDialog'
scope:$scope,
data:x,
closeByDocument:true
});
}
vm.getProductDetails();
}]);
Service:
app.factory("productService",["$http",function($http){
return {
getData: function() {
return $http.get("http://xxxxxxx/xxx/xxxxx");
}
};
}]);
DemoController.html
/* <table>
<tr>
<th>Brand</th>
<th>Price</th>
<th>OPerating System</th>
<th>Open ngDialog</th>
</tr>
<tr ng-repeat="x in vm.products">
<td ng-bind="x.brand"></td>
<td ng-bind="x.price| currency:"₹":2"></td>
<td ng-bind="x.os"></td>
<td><button ng-click="vm.productPopup(x)"></button></td>
</tr>
</table>
*/
ProductDialog.html:
<div class="ProductDetailsDialog">
<div class="ngdialog-content" role="document">
<div class="modal-header">
<button type="button" class="close" ng-click="ngDialog.close();">×</button>
<h4 class="modal-title">Product Detials</h4>
</div>
// <pre>{{vm|json}}</pre> //
<div class="modal-body">
<h4>Brand:<span ng-bind="ngDialogData.brand"></span></h4>
<h4>Price:<span ng-bind="ngDialogData.price | currency:"₹":2"></span></h4>
<p>Operating System:<span ng-bind="ngDialogData.os"></span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default">OK</button>
</div>
</div>
</div>

Getting data from modal AngularJS

I am trying to get data FROM modal to invoking controller, and all the examples I have found only describe way to get data to modal.
What is the proper way to do it?
This is a form I am using in modal:
<form class="form-horizontal">
<div class="modal-body">
<div class="control-group">
<label class="control-label">Name:</label>
<div class="controls">
<input type="text" ng-model="transaction.name" placeholder="Transaction name" />
</div>
</div>
<div class="control-group">
<label class="control-label">Category</label>
<div class="controls">
<input type="text" ng-model="transaction.category" placeholder="Category" />
</div>
</div>
<div class="control-group">
<label class="control-label">Amount</label>
<div class="controls">
<input type="text" ng-model="transaction.amount" placeholder="Amount" />
</div>
</div>
<div class="control-group">
<label class="control-label">Date</label>
<div class="controls">
<input type="text" datepicker-popup="dd-MMMM-yyyy" ng-model="transaction.date" is-open="opened" min="minDate" max="'2015-06-22'" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" />
<button class="btn" ng-click="open()"><i class="icon-calendar"></i></button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn pull-left" data-dismiss="modal">
<i class="icon-remove"></i> Cancel
</button>
<button type="submit" class="btn btn-primary" ng-disabled="pwError || incomplete" data-dismiss="modal" ng-click="createTransaction()">
<i class="icon-ok icon-white"></i> Save Changes
</button>
</div>
These are controllers:
moneyApp.controller("TransactionController", function($scope, $http, $modal, $log) {
console.log("modal: ", $modal);
$scope.transaction = {}
$scope.open = function() {
var modalInstance = $modal.open({
templateUrl: 'partials/modal.html',
controller: 'ModalInstanceController',
resolve: {
transaction: function() {
return $scope.transaction;
}
}
});
modalInstance.result.then(function (receivedTransaction) {
$scope.selected = receivedTransaction;
console.log("Transaction received: ", transaction);
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$http({method: 'GET', url: 'transactions/15/all/'}).success(function(data) {
$scope.transactions = data; // response data
});
})
and
moneyApp.controller("ModalInstanceController", function($scope, $modalInstance, $http, transaction) {
$scope.createTransaction = function() {
console.log("Transakcja: ", $scope.transaction);
$scope.transaction.budgetId = 15;
$scope.selected = {
item: $scope.transaction
}
$http({method: 'POST', url: 'transactions/add/', data : $scope.transaction, headers:{'Accept': 'application/json', 'Content-Type': 'application/json; ; charset=UTF-8'}}).success(function(data) {
console.log("Transaction succesfully added to a DB...");
});
}
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
When I am trying to invoke method createTransaction, $scope.transaction is undefined. How to get data from this form?
I think you need to assign transaction to $scope.transaction in your ModalInstanceController because you are passing in the transaction object but not putting it into $scope.
$scope.transaction = transaction
In your Modal form you need to pass the ng-model object(ie transaction) to the function (createTransaction()) which gets called on form submit.
<button type="submit" class="btn btn-primary" ng-disabled="pwError || incomplete" data-dismiss="modal" ng-click="createTransaction(transaction)">
<i class="icon-ok icon-white"></i> Save Changes
</button>
And in your controller add the object as parameter to the java-script function.
$scope.createTransaction = function(transaction) {
console.log("transaction details: "+ transaction.category+" "+transaction.amount);
};
Let me know if you are facing any issues, i can share the working code of mine.

Categories

Resources