how to save json array in mongodb using nodejs - javascript

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>

Related

AngularJs- Redirect to another view after submitting data to the server

I'm developing a small AngularJs and ASP.net MVC based web application with MongoDb database. And one of it's task is to register yourself if not an already a member. And after successfully submitting data from client side to the server, the user should be redirected to another page.So Data get saved in the database after the submission but It's does not seem to trigger the success function of Angular part where i try to redirect to the other page.
I have attached the image showing non-triggering part of the code highlighting in yellow.
How can i resolve this ? Any help would be appreciated.
[HttpPost]
public JsonResult RegisterUser(User user)
{
mongoClient = new MongoClient();
var db = mongoClient.GetDatabase(Database);
userList = db.GetCollection<User>("user");
var result = userList.AsQueryable().Where(a => a.UserName.Equals(user.UserName)).SingleOrDefault();
user.IsActive = true;
user.UserType = "Visitor";
string message = "";
if (result == null)
{
var seralizedUser = JsonConvert.SerializeObject(userList);
userList.InsertOne(user);
//var seralizedUser = new JavaScriptSerializer().Serialize(userList);
message = "Success";
//return Json(seralizedUser, JsonRequestBehavior.AllowGet);
return Json(new
{
redirectUrl = Url.Action("VisitorChatPanel", "Visitor", ""),
isRedirect = true
});
// return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
else
{
message = "Failed";
//var seralizedUser = new JavaScriptSerializer().Serialize(userList);
var seralizedUser = JsonConvert.SerializeObject(userList);
// return Json(seralizedUser, JsonRequestBehavior.AllowGet);
return Json(new
{
redirectUrl = Url.Action("VisitorChatPanel", "Visitor", ""),
isRedirect = false
});
}
}
angular.module('MyApp', [])
.controller('VisitorRegistrationController', function ($scope, RegistrationService) {
$scope.SubmitText = "Save";
$scope.IsFormValid = false;
$scope.Submitted = false;
$scope.Message = '';
$scope.User = {
UserName: '',
Password: '',
Email: '',
FirstName: '',
LastName: '',
IsActive: false,
UserType: 'Visitor'
};
//validates form on client side
$scope.$watch('f1.$valid', function (newValue) {
$scope.isFormValid = newValue;
});
//Save Data
$scope.SaveData = function (data) {
if ($scope.SubmitText == 'Save') {
$scope.Submitted = true;
$scope.Message = '';
if ($scope.isFormValid) {
// $scope.SubmitText = 'Please Wait...';
$scope.User = data;
alert('data : ' + $scope.User.FirstName);
RegistrationService.SaveFormData($scope.User).then(function (d) {
alert(d);
if (d == 'Success') {
//have to clear form here
ClearForm();
}
$scope.SubmitText = "Save";
});
}
else {
$scope.Message = '';
}
}
}
//Clear Form
function ClearForm() {
$scope.User = {};
$scope.f1.$setPristine(); //here f1 is form name
$scope.Submitted = false;
}
}).factory('RegistrationService', function ($http, $q) {
var fac = {};
fac.SaveFormData = function (data) {
//alert('$http : ' + $http);
var defer = $q.defer();
alert('q : ' + $q);
$http({
url: '/Visitor/RegisterUser',
method: 'POST',
data: JSON.stringify(data),
headers: {'content-type' : 'application/json'}
}).success(function (d) {
// Success callback
alert('Successfully registered !');
if (d.isRedirect) {
window.location.href = d.redirectUrl;
}
defer.resolve(d);
}).error(function (e) {
//Failed Callback
alert('Error!');
// defer.reject(e);
});
return defer.promise;
//return 'Successfull';
}
return fac;
});
;
#{
ViewBag.Title = "VisitorRegistrationForm";
}
<style>
body {
margin-top: 50px;
}
input {
max-width: 300px;
}
.error {
color: red;
}
</style>
<h2>Visitor Registration Form</h2>
<div class="panel panel-info" style="margin-left:30px;margin-right:500px;">
<div ng-controller="VisitorRegistrationController" class="panel-body">
<form novalidate name="f1" ng-submit="SaveData(User)" class="form-horizontal">
<div class="form-group">
<label class="text text-info col-md-offset-2">First Name : </label>
<input type="text" ng-model="User.FirstName" class="form-control col-md-offset-2" name="uFirstName" ng-class="Submitted?'ng-dirty':''" required autofocus />
<span class="error col-md-offset-2" ng-show="(f1.uFirstName.$dirty || Submitted) && f1.uFirstName.$error.required">FirstName required!</span>
</div>
<div class="form-group">
<label class="text text-info col-md-offset-2">Last Name : </label>
<input type="text" ng-model="User.LastName" class="form-control col-md-offset-2" name="uLastName" ng-class="Submitted?'ng-dirty':''" required autofocus />
<span class="error col-md-offset-2" ng-show="(f1.uLastName.$dirty || Submitted) && f1.uLastName.$error.required">LastName required!</span>
</div>
<div class="form-group">
<label class="text text-info col-md-offset-2">Email : </label>
<input type="email" ng-model="User.Email" class="form-control col-md-offset-2" name="uEmail" ng-class="Submitted?'ng-dirty':''" />
<span class="error col-md-offset-2" ng-show="(f1.uEmail.$dirty || Submitted) && f1.uEmail.$error.required">Email required</span>
<span class="error col-md-offset-2" ng-show="(f1.uEmail.$dirty || Submitted) && f1.uEmail.$error.email">Email not valid!</span>
</div>
<div class="form-group">
<label class="text text-info col-md-offset-2">UserName : </label>
<input type="text" ng-model="User.UserName" class="form-control col-md-offset-2" name="uUserName" ng-class="Submitted?'ng-dirty':''" required />
<span class="error col-md-offset-2" ng-show="(f1.uUserName.$dirty || Submitted) && f1.uUserName.$error.required">UserName required!</span>
</div>
<div class="form-group">
<label class="text text-info col-md-offset-2">Password : </label>
<input type="password" ng-model="User.Password" class="form-control col-md-offset-2" name="uPassword" ng-class="Submitted?'ng-dirty':''" required />
<span class="error col-md-offset-2" ng-show="(f1.uPassword.$dirty || Submitted) && f1.uPassword.$error.required">Password required!</span>
</div>
<div class="form-group">
<label></label>
<input type="submit" class="btn btn-success col-md-offset-2" value="{{SubmitText}}" />
</div>
</form>
</div>
</div>

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,

Add image to a list item in AngularJS

I have a simple shopping list and need to be able to upload an image to individual list items. Using MongoDB and AngularJS.
The image should be bound to the $scope.list.items therefore adding an image to a list item (eg. a picture of bread). How can I upload an image and bind it as part of that object? Basically the list of items would also contain images once this is complete.
HTML for displaying items:
<ul class="list-group">
<li style="color:{{list.color}}" class="list-group-item" ng-repeat="item in list.items | orderBy:propertyName:reverse | filter: search ">
<input type="checkbox" ng-model="item.isChecked" ng-click="editItem()">
{{item.name}} - {{item.priority}}
<i class="fa fa-trash-o" aria-hidden="true" ng-click="removeItem(item)"></i>&nbsp
<i class="fa fa-pencil" aria-hidden="true" href ng-click="showEdit = !showEdit" ng-show="!showEdit"></i><br>
<small class="form-text text-muted">Note: {{item.note}}</small>
<div ng-show = "showEdit">
<h4>Edit {{item.name}}</h4>
<form ng-submit="editItem()">
<input class="form-control" type="text" name="name" id="name" ng-model="item.name" maxlength="25" required>
<select class="form-control" name="priority" id="priority" ng-model="item.priority" required>
<option value="">Priority</option>
<option value="High">High</option>
<option value="Low">Low</option>
</select>
<input type="text" class="form-control" name="note" id="note" ng-model="item.note" maxlength="255" value= " ">
<button class="btn btn-default" type="submit" ng-click="showEdit = !showEdit">Update</button>
</form>
</div>
<br>
</li>
</ul>
Here is the HTML for adding an item:
<button class="btn btn-default btn-custom" href ng-click="showAddItem = !showAddItem" ng-show="!showAddItem">Add Item</button>
<div ng-show="showAddItem" class="add-item">
<h4>Add Item</h4>
<form ng-submit="addItem()">
<input class="form-control" type="text" name="name" id="name" ng-model="newItem.name" placeholder="Item" maxlength="25" required>
<select class="form-control" name="priority" id="priority" ng-model="newItem.priority" required>
<option value="">Priority</option>
<option value="High">High</option>
<option value="Low">Low</option>
</select>
<input type="text" class="form-control" name="note" id="note" ng-model="newItem.note" placeholder="Note" maxlength="255" value= " ">
<button class="btn btn-default btn-add" type="submit">Add</button>&nbsp<span class="close-box" ng-click="showAddItem = !showAddItem"><u>close</u></span>
</form>
<!-- <button class="btn btn-default btn-lg btn-custom" href="">Add Item</button> -->
</div><br><br>
<a ng-href="#/home"><button class="btn btn-default btn-lg btn-home">Save & Return</button></a>
</div>
And the controller for adding an item:
(function () {
'use strict';
var app = angular.module('myApp');
app.controller('ShoppingListController', ['$scope', '$http', '$routeParams', 'API_BASE', '$location', function($scope, $http, $routeParams, API_BASE, $location){
// GET SPECIFIC LIST
$scope.list = [];
var id = $routeParams.id;
$http({
method: 'GET',
url: API_BASE + 'shopping-lists/' + id
}).then(function successCallback(response) {
$scope.list = response.data[0];
}, function errorCallback(response) {
console.log('it did not work');
console.log(response.statusText);
});
// REMOVE LIST
$scope.removeList = function(){
var id = $scope.list.id;
console.log(id);
$http.delete(API_BASE + 'shopping-lists/' + id)
.success(function (data, status, headers, config) {
console.log('you deleted :' + $scope.list);
})
.error(function (data, status, header, config) {
});
$location.path('/home');
};
// RANDOM ID
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 20; i++ ){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
text += Date.now();
return text;
}
// ADD ITEM
$scope.addItem = function(){
var created = new Date();
var newID = makeid();
if($scope.list.hasOwnProperty('items') === false){
$scope.list.items = [];
}
$scope.list.items.push({
name : $scope.newItem.name,
priority : $scope.newItem.priority,
note: $scope.newItem.note,
isChecked: false,
listId: $scope.list.id,
created: created,
id: newID
});
// console.log($scope.list.items);
$http.put(API_BASE + 'shopping-lists/', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
// Reset input fields after submit
$scope.newItem = {
name: "",
priority: "",
note: ""
};
I modified your code to add an image to the list, and then altered the list item display to check for properties:
<input type="checkbox" ng-model="item.isChecked" ng-click="editItem()" ng-show="item.hasOwnProperty('isChecked')">
<img ng-show="item.hasOwnProperty('imageSrc')" src="{{ item.imageSrc }}" />
And I made a simple function to add an image item that has an imageSrc property, used in the image that only appears if that property is set.
$scope.list.items.push({
imageSrc: 'http://lh5.googleusercontent.com/-QErodXkgwBc/AAAAAAAAAAI/AAAAAAAAAWQ/LPUidgUqYHs/photo.jpg?sz=32',
priority: '',
note: 'Evan',
//don't include this property - which will make the ng-show for the checkbox false
//isChecked: true,
created: new Date(),
id: -1
});
. This is one way to do it but you could do it differently.
Sample
'use strict';
var app = angular.module('myApp', ['ngRoute']);
app.constant('API_BASE','/api');
app.config(['$routeProvider', function($routeProvider) {}]);
app.controller('ShoppingListController', ['$scope','$http', '$routeParams', 'API_BASE', '$location', function($scope, $http, $routeParams, API_BASE, $location){
// GET SPECIFIC LIST
$scope.list = {items: []};
$scope.showAddItem = true;
var id = $routeParams.id;
//commenting this out because we don't have access to your server
/*$http({
method: 'GET',
url: API_BASE + 'shopping-lists/' + id
}).then(function successCallback(response) {
$scope.list = response.data[0];
}, function errorCallback(response) {
console.log('it did not work');
console.log(response.statusText);
});*/
// REMOVE LIST
$scope.removeList = function(){
var id = $scope.list.id;
console.log(id);
$http.delete(API_BASE + 'shopping-lists/' + id)
.success(function (data, status, headers, config) {
console.log('you deleted :' + $scope.list);
})
.error(function (data, status, header, config) {
});
$location.path('/home');
};
// RANDOM ID
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 20; i++ ){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
text += Date.now();
return text;
}
// ADD ITEM
$scope.addItem = function(){
var created = new Date();
var newID = makeid();
if($scope.list.hasOwnProperty('items') === false){
$scope.list.items = [];
}
$scope.list.items.push({
name : $scope.newItem.name,
priority : $scope.newItem.priority,
note: $scope.newItem.note,
isChecked: false,
listId: $scope.list.id,
created: created,
id: newID
});
// console.log($scope.list.items);
$http.put(API_BASE + 'shopping-lists/', $scope.list)
.success(function (data, status, headers, config) {
})
.error(function (data, status, header, config) {
});
// Reset input fields after submit
$scope.newItem = {
name: "",
priority: "",
note: ""
};
};
$scope.addImage = function(){
if($scope.list.hasOwnProperty('items') === false){
$scope.list.items = [];
}
$scope.list.items.push({
imageSrc: 'http://lh5.googleusercontent.com/-QErodXkgwBc/AAAAAAAAAAI/AAAAAAAAAWQ/LPUidgUqYHs/photo.jpg?sz=32',
priority: '',
note: 'Evan',
//don't include this property - which will make the ng-show for the checkbox false
//isChecked: true,
created: new Date(),
id: -1
});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
<div ng-app="myApp" ng-controller="ShoppingListController">
<script src="script.js"></script>
<button class="btn btn-default btn-custom" href ng-click="showAddItem = !showAddItem" ng-show="!showAddItem">Add Item</button>
<div style="font-style: italic">//code for adding item
<ul class="list-group">
<li style="color:{{ list.color }}" class="list-group-item" ng-repeat="item in list.items | orderBy:propertyName:reverse | filter: search ">
<input type="checkbox" ng-model="item.isChecked" ng-click="editItem()" ng-show="item.hasOwnProperty('isChecked')">
<img ng-show="item.hasOwnProperty('imageSrc')" src="{{ item.imageSrc }}" />
{{item.name}} - {{ item.priority }}
<i class="fa fa-trash-o" aria-hidden="true" ng-click="removeItem(item)"></i>
<i class="fa fa-pencil" aria-hidden="true" href ng-click="showEdit = !showEdit" ng-show="!showEdit"></i><br>
<small class="form-text text-muted">Note: {{ item.note }}</small>
<div ng-show = "showEdit">
<h4>Edit {{ item.name }}</h4>
<form ng-submit="editItem()">
<input class="form-control" type="text" name="name" id="name" ng-model="item.name" maxlength="25" required>
<select class="form-control" name="priority" id="priority" ng-model="item.priority" required>
<option value="">Priority</option>
<option value="High">High</option>
<option value="Low">Low</option>
</select>
<input type="text" class="form-control" name="note" id="note" ng-model="item.note" maxlength="255" value= " ">
<button class="btn btn-default" type="submit" ng-click="showEdit = !showEdit">Update</button>
</form>
</div>
<br>
</li>
</ul>
<button ng-click="addImage()" >Add image</button></div>

MEAN : Getting Error 400 (Bad Request) on POST

I am fairly new to the MEAN Stack, and after following this tutorial : http://www.bradoncode.com/tutorials/mean-stack-tutorial-part-4-angularjs/, I was trying to make my own web application to send and receive invoices. I have a localhost:3000/invoices page set up which is currently empty ([ ]). I am trying to fill out a form and post to it localhost:3000/invoices so that the MongoDB database is populated. My MongoDB process is constantly running. This is the Model outlining all the fields I require in a record :
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
validation = require('./validation.server.model');
/**
* Invoices Schema
*/
var InvoiceSchema = new Schema({
invoice_date: {
type: Date,
default: Date.now
},
from_entity: {
type: String,
default: '',
trim: true,
required: 'legal entity cannot be blank'
},
from_service: {
type: String,
default: '',
trim: true,
required: 'service line cannot be blank'
},
country: {
type: String,
default: '',
trim: true,
required: 'country cannot be blank'
},
to_entity: {
type: String,
default: '',
trim: true,
required: 'legal entity cannot be blank'
},
to_service: {
type: String,
default: '',
trim: true,
required: 'service line cannot be blank'
},
partner: {
type: String,
default: '',
trim: true,
required: 'partner cannot be blank'
},
invoice_number: {
type: String,
default: '',
trim: true,
unique: true,
required: 'invoice number cannot be blank'
},
currency: {
type: String,
default: '',
trim: true,
required: 'currency cannot be blank'
},
amount: {
type: Number,
default: '',
trim: true,
required: 'amount cannot be blank'
}
});
mongoose.model('Invoice', InvoiceSchema);
This is my invoice client side controller :
'use strict';
// Invoices controller
angular.module('invoices').controller('InvoicesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Invoices', '$filter',
function($scope, $stateParams, $location, Authentication, Invoices, $filter) {
$scope.authentication = Authentication;
$scope.currentPage = 1;
$scope.pageSize = 10;
$scope.offset = 0;
// Page changed handler
$scope.pageChanged = function() {
$scope.offset = ($scope.currentPage - 1) * $scope.pageSize;
};
// Create new Invoice
$scope.create = function() {
var invoice = new Invoices ({
amount: this.amount,
invoice_number: this.invoice_number,
partner: this.partner,
to_service: this.to_service,
to_entity: this.to_entity,
country: this.country,
from_service: this.from_service,
from_entity: this.from_entity
});
// Redirect after save
invoice.$save(function(response) {
$location.path('invoices/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Invoice
$scope.remove = function(invoice) {
if (invoice) {
invoice.$remove();
for (var i in $scope.invoices) {
if ($scope.invoices [i] === invoice) {
$scope.invoices.splice(i, 1);
}
}
} else {
$scope.invoice.$remove(function() {
$location.path('invoices');
});
}
};
// Update existing Invoice
$scope.update = function() {
var invoice = $scope.invoice;
invoice.$update(function() {
$location.path('invoices/' + invoice._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Invoices
$scope.find = function() {
$scope.invoices = Invoices.query();
};
// Find existing Invoice
$scope.findOne = function() {
$scope.invoice = Invoices.get({
invoiceId: $stateParams.invoiceId
});
};
// Search for a Invoice
$scope.invoiceSearch = function(invoice) {
$location.path('invoices/' + invoice._id);
};
}
]);
And this is a simple form in AngularJS on the front-end :
<section data-ng-controller="InvoicesController">
<div class="page-header">
<h1>New Invoice</h1>
</div>
<div class="col-md-12">
<form class="form-horizontal" data-ng-submit="create()" novalidate>
<fieldset>
<div class="form-group">
<label class="control-label" for="invoice_number">Invoice Number</label>
<div class="controls">
<input type="text" data-ng-model="invoice.invoice_number" id="invoice_number" class="form-control" placeholder="Invoice Number" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="amount">Amount</label>
<div class="controls">
<input type="text" data-ng-model="invoice.amount" id="amount" class="form-control" placeholder="Amount" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="currency">Currency</label>
<div class="controls">
<input type="text" data-ng-model="invoice.currency" id="currency" class="form-control" placeholder="Currency" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="partner">Partner</label>
<div class="controls">
<input type="text" data-ng-model="invoice.partner" id="partner" class="form-control" placeholder="Partner" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="country">Country</label>
<div class="controls">
<input type="text" data-ng-model="invoice.country" id="name" class="form-control" placeholder="Country" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="to_service">Service Line (To:)</label>
<div class="controls">
<input type="text" data-ng-model="invoice.to_service" id="to_service" class="form-control" placeholder="Service Line (To:)" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="from_service">Service Line (From:)</label>
<div class="controls">
<input type="text" data-ng-model="invoice.from_service" id="from_service" class="form-control" placeholder="Service Line (From:)" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="to_entity">Entity(To:)</label>
<div class="controls">
<input type="text" data-ng-model="invoice.to_entity" id="to_entity" class="form-control" placeholder=" Entity (To:)" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="from_entity">Entity(From:)</label>
<div class="controls">
<input type="text" data-ng-model="invoice.from_entity" id="from_entity" class="form-control" placeholder=" Entity (From:)" required>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
<div data-ng-show="error" class="text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>
</section>
When I proceed and submit the form I get the following :
Amount is a required field as evident through the model, and I am always certain to fill in that value. I have typed numbers and decimals always, yet is says that field is required and displays Bad Request. Also whenever I do npm start, my application loads up without any errors. I have attempted watching several youtube tutorials, but none clarify the reason for this not working. Swift Help would be greatly appreciated :)
EDIT : When I remove the required from the Model, the transaction goes through, but none of the values inputted into the form are recorded, only the invoice date is.
You get a date because there is a default set for that. Define $scope.invoice = {} in your controller so that it is bound to your view (2-way). Then, change all fetches from $scope.invoice. For example:
$scope.invoice = {};
$scope.create = function() {
var invoice = new Invoices ({
amount: $scope.invoice.amount,
invoice_number: $scope.invoice.invoice_number,
partner: $scope.invoice.partner,
...
});
...
};

angular resource passing unwanted parameters

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' } }
});
}])

Categories

Resources