I have a form, it sends data to a database, but it makes it twice.
Here is the code of controller and example of html view.
$scope.addEvent = function(type) {
if (!$scope.sentAdd) {
$scope.newEvent.admission = type;
$scope.newEvent.customer_id = $scope.curUID;
console.log($scope.newEvent);
$http({
url: '/addEvent',
method: "POST",
data: $.param($scope.newEvent),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
.success(function(data){
//console.log(data);
$scope.newEvent = $scope.cleanEvent;
$scope.addEventForm.$setPristine();
$scope.sentType = type;
$scope.sentAdd = true;
$.fancybox.close();
$.fancybox.open({ href: '#eventSuccess', type: 'inline' });
});
}
};
<form name="addEventForm" novalidate>
<input type="text" ng-model="text">
<a ng-click="addEvent('Paid')">Add Paid Event</a><br>
<a ng-click="addEvent('Free')">Add Free Event</a>
</form>
Related
In HTML i have some customer registration fields
<input type="text" ng-model="customer.fname">
<input type="text" ng-model="customer.lname">
<input type="text" ng-model="customer.username">
My angular controller code
var customerInformation = $scope.customer;
customerInformation = JSON.stringify($scope.customer);
$http({
method: 'POST',
url: 'person/registrationCustomer',
data: customerInformation,
timeout: 4000
})
.then(function (success) {
}, function (error) {
});
Try this:
var customerInformation = $scope.customer;
$http.post('person/registrationCustomer',customerInformation)
.then(function (success) {
}, function (error) {
});
Yes, your data should be mapped to an object, have a look:
var dataObj = {
customerInformations : $scope.customer;
};
$http({
method: 'POST',
url: 'person/registrationCustomer',
data: dataObj,
timeout: 4000
})
I am trying to send data from my Angular.js controller to Node.js backend. I succeeded in making a MongoDB entry when the request is raised.But the data is missing in the MongoDB entry. I am stuck and can't proceed with my app anymore. Can anyone give me a clear explanation why I am not able to send the form data to the Node.js.
I had put my schema of the data here:
var common = require('../common');
var inviteeSchema = common.Schema({
email: String
});
var Invite = common.conn.model('Invite', inviteeSchema);
module.exports = Invite;
I have enclosed the routing code here.
router.route('/addtoinvitelist').post(function (req, res, next) {
var invite =new Invite(req.body);
invite.save(function(err,email){
if(err) throw err;
res.json({message:"your mail id is stored in our database we will soon send you an invite"})
});
});
My HTML form goes here
<form action="#">
<div class="form-group">
<label for="subcribeNewsletter" class="control-label">INVITE FORM<br> <small>We are happy to invite you to medicoshere, So please enter your email ID in the below form.</small></label>
<div class="input-group input-group-in input-group-sm">
<div class="input-group-addon"><i class="fa fa-envelope text-belpet"></i></div>
<input class="form-control" id="subcribeNewsletter" placeholder="name#mail.com" ng-model="useremail" required>
<div class="input-group-btn">
<button type="submit" class="btn btn-default text-belpet" ng-click="AddToInviteList(useremail)"><strong>OK</strong></button>
</div>
</div>
</div><!-- /.form-group -->
</form><!-- /form -->
my angular service functions goes here
`this.AddToInviteList = function (email, cb) {
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}, // set the headers so angular passing info as form data (not request payload)
data:"email"
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
}`
Controller function is here
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.email = {};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
});
Pass email as json object { 'email' : email }.
Just try this code:
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
Controller :
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
$scope.user = {
email : $scope.useremail
};
UserServices.AddToInviteList($scope.user, function (dataresponse) {
console.log(dataresponse);
})
}
});
In server side you can access the email by calling 'req.body.email'
Change your model name in HTML input element with email and send request as
$http({
method: 'POST',
url: "http://localhost:3000/users/addtoinvitelist",
headers: {
'Content-Type': 'application/json'
},
data:{ 'email' : email }
}).success(function (data) {
console.log("email is posted sucessfully" + data);
cb(data);
})
and get it at backend side as
req.body.email
I think that should work!
Update
App.controller('InviteController', function ($scope, $rootScope, $routeParams, $location, UserServices) {
$scope.init = function () {
console.log("hii this is a test ")
};
$scope.AddToInviteList = function () {
UserServices.AddToInviteList($scope.email, function (dataresponse) {
console.log(dataresponse);
})
}
I have what would seem to be a simple problem with AngularJS - apologies if so. I'm new and have searched all over and can't quite find an answer to what I want to do.
Basically I have a $http request that is getting a list of 'Cards' from a server which I'm then using ng-repeat to build in the HTML. I then want to populate those Cards with a number of 'Metrics' - also retrieved from the server. I have a controller for the 'Cards' (parents) and a separate controller for the 'Metrics' (children).
My issue is that I can't work out how to reference the ID of the parent 'Card' when making the child $http request.
Below is the HTML & JS that I am using - any help would be appriciated:
HTML:
<div class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
<div ng-repeat="Card in Dashboard.DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric">
<div ng-repeat="Metric in Metric.DashboardMetrics">
{{Metric.MetricDisplayName}}
</div>
</div>
</div>
</div>
JS:
(function () {
var app = angular.module('OtterDashboard', [ ]);
app.controller('DahsboardCardController', [ '$http', function($http) {
//Declare a varaible for the data
var DashboardCards = this;
//Set the varaiable to an empty array to receive the data
DashboardCards.DashboardCards = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardCards.DashboardCards = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card) {
//Declare a varaible for the data
var DashboardMetrics = this;
//Set the varaiable to an empty array to receive the data
DashboardMetrics.DashboardMetrics = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + **???reference to parent card ID???** + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Metric data could not be retrieved');
});
}]);
})();
Thank you!
EDIT 1
Use a service for shared variable between controllers. Look the example:
app.controller('DahsboardCardController', ['$http', function($http, $sharedResource) {
var DashboardCards = this;
DashboardCards.DashboardCards = [ ];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardCards.DashboardCards = data.data.d.results;
$sharedResource.set("id", "<pass id value>");
}, function errorCallback(response) {
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card, $sharedResource) {
var DashboardMetrics = this;
DashboardMetrics.DashboardMetrics = [];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + $sharedResource.get("id") + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
console.log('Metric data could not be retrieved');
});
}]);
app.factory('$sharedResource', function () {
var property = {};
return {
get: function (key) {
return property[key];
},
set: function(key, value) {
property[key] = value;
}
};
});
EDIT 2
When working with angularjs is recomended use a one object for print object in table. Why this is a beautiful s2.
Look this example. To help you in development. Use the sample function pass the parentId in load(CardId). This function will run in the page load.
I too fix code html. You used the alias controller before input field of same.
var app = angular.module("App", []);
app.controller('DahsboardCardController', ['$scope', function($scope) {
$scope.DashboardCards = [{
CardId: "111",
CardDisplayName: "Card 1"
}, {
CardId: "222",
CardDisplayName: "Card 2"
}, {
CardId: "333",
CardDisplayName: "Card 3"
}];
}
]);
app.controller('DahsboardMetricController', ['$scope', function($scope) {
$scope.load = function(CardIdParent) {
console.log(CardIdParent);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
{{Dashboard.DashboardCards}}
<div ng-repeat="Card in DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric" ng-init="load(Card.CardId)">
This a id parent: {{Card.CardId}}
<div ng-repeat="MetricItem in DashboardMetrics">
{{MetricItem.MetricDisplayName}}
</div>
</div>
</div>
</div>
</div>
ng-show="my.message" is set to true in http success but it doesn't update the view.
Here is my code:
Controller Js:
lgControllers.controller('FormCtrl', function($scope, $http) {
$scope.my = {
message: false
};
$scope.submitForm = function() {
$http({
url: "../saket/ajax.php",
data: "email_id=" + $scope.form.emailaddress + "&category_id=" + cat_num + "&action=subscribe",
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data) {
$scope.my = {
message: true
};
console.log(data); // http is success
console.log($scope.my.message); // gives true
}).error(function(err) {
"ERR", console.log(err)
})
};
});
Index.html:
<div ng-controller="FormCtrl">
<div ng-show="my.message">It worked!</div>
</div>
my.message gives true in console but the div remains hidden in the view.
I can't figure out where the problem is.
Can it be that you are overwriting the message property, and angularjs is loosing the reference?
$scope.my = {
message: true
;
try just :
$scope.my.message = true;
I have two functions in my Controller.
The showEditScreen function which actually loads a user record over
$resource.get.
The updateUserDetails function which should update the user.
In the showEditScreen function everything is working. The user details are parsed over json and when looking at the $scope.user object functions like $get, $post, $update are present.
When looking at the same (also unmodified) object in the updateUserDetails function the object has changed and all the functions like $get, $post, $update and so on are missing.
This is a really weird behavior. Does anybody have an explanation for this?
When I use http.put i can save the object by the way.
console.log($scope.user) output in showEditScreen() function
Resource {$get: function, $save: function, $query: function, $remove: function, $delete: function…}
firstName: "Mista"
id: "d419375a-ba0b-4177-93cf-842e2c3e046e"
lastName: "BlaaahBlaaah1"
password: "bla"
roles: Array[2]
username: "blabla1"
__proto__: Resource
console.log($scope.user) in updateUserDetails() function:
Resource {id: "d419375a-ba0b-4177-93cf-842e2c3e046e", firstName: "Mista", lastName: "BlaaahBlaaah1", username: "blabla1", password: "bla"…}
firstName: "Mista"
id: "d419375a-ba0b-4177-93cf-842e2c3e046e"
lastName: "BlaaahBlaaah1"
password: "bla"
roles: Array[2]
username: "blabla1"
__proto__: Resource
When executing $scope.user.$update() in updateUserDetails() function:
POST http://localhost:8080/api/user/.json 405 (Request method 'POST' not supported) angular.js:9120
(anonymous function) angular.js:9120
sendReq angular.js:8977
$http angular.js:8768
Resource.(anonymous function) angular-resource.js:385
Resource.(anonymous function) angular-resource.js:431
UserCtrl.$scope.updateUserDetails controllers.js:37
(anonymous function) angular.js:6212
(anonymous function) angular.js:12751
Scope.$eval angular.js:7905
Scope.$apply angular.js:7985
$delegate.__proto__.$apply index.html:500
(anonymous function) angular.js:12750
(anonymous function) angular.js:1928
forEach angular.js:110
eventHandler angular.js:1927
HTML:
<div id="user_list" class="listview_list">
<div id="user_row" class="listview_row" ng-repeat="user in users">
<div id="user_username" class="listview_column"><span class="listview_fat"> {{user.username}}</span></div>
<div id="user_firstname" class="listview_column">{{user.firstName}}</div>
<div id="user_lastname" class="listview_column">{{user.lastName}}</div>
<button class="listview_row_button" ng-click="showEditScreen(user.id)">Edit</button>
</div>
</div>
<div id="user_edit" class="edit_form" ng-show="userEditScreenIsVisible">
<form name="edit_user">
<label>Username</label><br/>
<input name="username" ng-model="user.username" required/><br/>
<label>Firstname</label><br/>
<input name="firstName" ng-model="user.firstName" required/><br/>
<label>Lastname</label><br/>
<input name="lastName" ng-model="user.lastName" required/><br/>
<button class="button" ng-click="hideEditScreen()">Close</button>
<button class="button" ng-click="updateUserDetails()">Update</button>
</form>
</div>
Controller:
/*
* Controller to display and manipulate users.
*/
function UserCtrl($scope, $http, Users, User) {
// set edit screen to invisible by default
$scope.userEditScreenIsVisible = false;
// set new screen to invisible by default
$scope.userNewScreenIsVisible = false;
// display list with users
Users.query(
{}, //params
function (data) { //success
$scope.users = data.data;
},
function (data) { //failure
console.log("Error occurred while getting list of users");
});
// show edit screen if edit button is clicked
$scope.showEditScreen = function(id) {
$scope.user = User.get({userId: id});
console.log($scope.user);
$scope.userEditScreenIsVisible = true;
}
// hide edit screen if close button is clicked
$scope.hideEditScreen = function() {
$scope.userEditScreenIsVisible = false;
}
$scope.updateUserDetails = function() {
console.log($scope.user);
$scope.user.$update();
//$http.put("http://localhost:8080/api/user/" + $scope.user.id + ".json", $scope.user);
}
// show new screen if add button is clicked
$scope.showNewScreen = function() {
$scope.userNewScreenIsVisible = true;
}
}
Service:
angular.module('user.services', ['ngResource']).
factory('Users', function($resource) {
return $resource('http://localhost\\:8080/api/user/all.json', {}, {
query: {method:'GET', params:{}, isArray:false}
});
}).
factory('User', function($resource){
return $resource('http://localhost\\:8080/api/user/:userId.json', {}, {
get: {method:'GET'},
update: {method:'PUT'}
});
})
Issue solved!!!!
Service:
// User Service
angular.module('user.services', ['ngResource']).
factory('User', function($resource){
return $resource('/api/user/:userId', {userId: '#id'}, {
query: {method: 'GET', headers: [{'Content-Type': 'application/json'}, {'Accept' : 'application/json'}]},
get: {method:'GET', headers: [{'Content-Type': 'application/json'}, {'Accept' : 'application/json'}]},
update: {method:'PUT', headers: [{'Content-Type': 'application/json'}, {'Accept' : 'application/json'}]}
});
})
The first problem was solved by Vineet. Actually the functions $get, $post, $delete and so on were present. Just further down when expanding the log record in the Chrome Batarang environment.
My actual problem was that the default query method does not like file extensions at the end such as .json
If using file extensions following will happen when not parsing an Id:
/api/user/.json
But we would like to have following to display all users:
/api/user/
So file extensions should not be used. The Content-Type should be negotiated through the header. Then file extensions won't be necessary to determine the Content-Type.
I changed my user.service the following way:
angular.module('user.services', ['ngResource']).
factory('User', function($resource){
return $resource('http://localhost\\:8080/api/user/:userId', {userId: '#id'}, {
query: {method: 'GET', headers: [{'Content-Type': 'application/json'}, {'Accept': 'application/json'}]},
get: {method:'GET', headers: [{'Content-Type': 'application/json'}, {'Accept': 'application/json'}]},
update: {method:'PUT', headers: [{'Content-Type': 'application/json'}, {'Accept': 'application/json'}]},
create: {method:'POST', headers: [{'Content-Type': 'application/json'}, {'Accept': 'application/json'}]},
delete: {method:'DELETE', headers: [{'Content-Type': 'application/json'}, {'Accept': 'application/json'}]}
});
})
My controller looks as followed:
function UserCtrl($scope, $resource, User) {
// set edit screen to invisible by default
$scope.userModScreenIsVisible = false;
// initialize buttons as invisible
$scope.updateUserDetailsButtonIsVisible = false;
$scope.saveUserDetailsButtonIsVisible = false;
// display list with users
$scope.getList = function() {
User.query(
{}, //params
function (data) { //success
$scope.users = data.data;
},
function (data) { //failure
console.log("Error occurred while getting list of users");
});
}
$scope.getList();
// show edit screen if edit button is clicked
$scope.showEditScreen = function(id) {
$scope.user = User.get({userId: id});
$scope.updateUserDetailsButtonIsVisible = true;
$scope.userModScreenIsVisible = true;
}
// hide edit screen if close button is clicked
$scope.hideEditScreen = function() {
$scope.updateUserDetailsButtonIsVisible = false;
$scope.saveUserDetailsButtonIsVisible = false;
$scope.userModScreenIsVisible = false;
}
// update a user
$scope.updateUserDetails = function() {
$scope.user.$update();
for(var i=0;i<$scope.users.length;i++) {
if($scope.users[i].id == $scope.user.id) {
angular.extend($scope.users[i], $scope.user);
break;
}
}
console.log($scope.user);
//$scope.user = User.get({userId: $scope.user.id});
$scope.updateUserDetailsButtonIsVisible = false;
$scope.userModScreenIsVisible = false;
}
// show a new user screen
$scope.showNewScreen = function() {
$scope.user = new User();
$scope.saveUserDetailsButtonIsVisible = true;
$scope.userModScreenIsVisible = true;
}
// save a new user
$scope.saveUserDetails = function() {
$scope.user.$create();
$scope.users.push($scope.user);
$scope.saveUserDetailsButtonIsVisible = false;
$scope.userModScreenIsVisible = false;
}
// delete a user
$scope.deleteUser = function(id) {
$scope.user = User.get({userId: id});
$scope.user.$delete();
}
}
The HTML:
<div id="user_list" class="listview_list">
<div id="user_row" class="listview_row" ng-repeat="u in users">
<div id="user_username" class="listview_column"><span class="listview_fat">{{u.username}}</span></div>
<div id="user_firstname" class="listview_column">{{u.firstName}}</div>
<div id="user_lastname" class="listview_column">{{u.lastName}}</div>
<button class="listview_row_button" ng-click="deleteUser(u.id)">Delete</button>
<button class="listview_row_button" ng-click="showEditScreen(u.id)">Edit</button>
</div>
</div>
<div id="user_new" class="new_user">
<button class="new_user_button" ng-click="showNewScreen()">Add user</button>
</div>
<div id="user_mod" class="mod_form" ng-show="userModScreenIsVisible">
<form name="mod_user">
<label>Username</label><br/>
<input name="username" ng-model="user.username"/><br/>
<label>Firstname</label><br/>
<input name="firstName" ng-model="user.firstName"/><br/>
<label>Lastname</label><br/>
<input name="lastName" ng-model="user.lastName"/><br/>
<button class="button" ng-click="hideEditScreen()">Close</button>
<button class="button" ng-click="updateUserDetails()" ng-show="updateUserDetailsButtonIsVisible">Update</button>
<button class="button" ng-click="saveUserDetails()" ng-show="saveUserDetailsButtonIsVisible">Save</button>
</form>
</div>