I have been working on a reddit clone from the thinkster.io tutorial, and I can not figure out how to save upvote values to the database. Could some one please take a look?
// from angularApp.js
.factory('posts', ['$http', 'auth', function($http, auth){
var o = {
posts: []
};
o.upvote = function(post) {
return $http.put('/posts/' + post._id + '/upvote', {
headers: {Authorization: 'Bearer '+auth.getToken()}
}).success(function(data){
post.votes += 1;
});
};
return o;
}])
.controller('MainCtrl', [
'$scope',
'posts',
'auth',
function($scope, posts, auth){
$scope.posts = posts.posts;
$scope.isLoggedIn = auth.isLoggedIn;
$scope.addPost = function(){
//prevents empty posts
if(($scope.title === '') || ($scope.body === '')) { return; }
//creates post
posts.create({
title: $scope.title,
votes: 0,
createdOn: Date.now(),
link: $scope.link,
body: $scope.body,
});
//returns empty values after post is created
$scope.title = '';
$scope.link = '';
$scope.body = '';
};
$scope.incrementUpvotes = function(post){
posts.upvote(post);
};
}])
//mongoose post schema
var PostSchema = new mongoose.Schema({
title: { type: String, required: '{PATH} is required!'},
body: String,
createdOn: { type: Date, default: Date.now },
votes: {type: Number, default: 0},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
author: String
});
PostSchema.methods.upvote = function(cb) {
this.votes += 1;
this.save(cb);
};
mongoose.model('Post', PostSchema);
// from index.js
// upvote a post
router.put('/posts/:post/upvote', auth, function(req, res, next) {
req.post.upvote(function(err, comment){
if (err) { return next(err); }
res.json(comment);
});
});
//from index.ejs (html)
<i ng-click="incrementUpvotes(post)" class="ion-chevron-up"></i><br>
{{comment.votes}}<br>
o.upvote = function(post) {
return $http.put('/posts/' + post._id + '/upvote', null, { ...
Related
I'm new to programming so I followed this tutorial http://www.mitechdev.com/2016/07/crud-operations-on-angular-ui-calendar.html, but it doesn't refresh the data after submitting the form. The new/modified/deleted data it's displayed after I refresh the page. I also tried ".fullCalendar( 'refetchEvents' )" but with no effect. Basically what I want to do is when I submit the form (closing the modal) the data to be displayed in the calendar. Thank you in advance.
Update - my script here:
<script>
var app = angular.module('myapp', ['ui.calendar', 'ui.bootstrap']);
app.controller('CalenderController', ['$scope', '$http', 'uiCalendarConfig', '$uibModal', function ($scope, $http, uiCalendarConfig, $uibModal) {
$scope.SelectedEvent = null;
var isFirstTime = true;
$scope.events = [];
$scope.eventSources = [$scope.events];
$scope.NewEvent = {};
//this function for get datetime from json date
function getDate(datetime) {
if (datetime != null) {
var mili = datetime.replace(/\/Date\((-?\d+)\)\//, '$1');
return new Date(parseInt(mili));
}
else {
return "";
}
}
// this function clears clender enents
function clearCalendar() {
if (uiCalendarConfig.calendars.myCalendar != null) {
uiCalendarConfig.calendars.myCalendar.fullCalendar('removeEvents');
uiCalendarConfig.calendars.myCalendar.fullCalendar('unselect');
}
}
//Load events from server to display on caledar
function populate() {
clearCalendar();
$http.get('/Test/GetEvents', {
cache: false,
params: {}
}).then(function (data) {
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function (value) {
$scope.events.push({
id: value.EventID,
title: value.Title,
description: value.Description,
start: new Date(parseInt(value.StartAt.substr(6))),
end: new Date(parseInt(value.EndAt.substr(6))),
allDay: value.IsFullDay,
stick: true
});
});
});
}
populate();
//UI- calendar configuration
$scope.uiConfig = {
calendar: {
//height: 450,
height: 650,
editable: true,
displayEventTime: true,
header: {
left: 'month,agendaWeek,agendaDay',
center: 'title',
right: 'today prev,next'
},
timeFormat: {
month: ' ', // for hide on month view
agenda: 'h:mm t'
},
selectable: true,
selectHelper: true,
select: function (start, end) {
var fromDate = moment(start).format('YYYY/MM/DD LT');
var endDate = moment(end).format('YYYY/MM/DD LT');
$scope.NewEvent = {
EventID: 0,
StartAt: fromDate,
EndAt: endDate,
IsFullDay: false,
Title: '',
Description: ''
}
$scope.ShowModal();
},
eventClick: function (event) {
$scope.SelectedEvent = event;
var fromDate = moment(event.start).format('YYYY/MM/DD LT');
var endDate = moment(event.end).format('YYYY/MM/DD LT');
$scope.NewEvent = {
EventID: event.id,
StartAt: fromDate,
EndAt: endDate,
IsFullDay: false,
Title: event.title,
Description: event.description
}
$scope.ShowModal();
},
eventAfterAllRender: function () {
if ($scope.events.length > 0 && isFirstTime) {
uiCalendarConfig.calendars.myCalendar.fullCalendar('gotoDate', $scope.events[0].start);
isFirstTime = false;
}
}
}
};
//This function shows bootstrap modal dialog
$scope.ShowModal = function () {
$scope.option = {
templateUrl: 'modalContent.html',
controller: 'modalController',
backdrop: 'static',
resolve: {
NewEvent: function () {
return $scope.NewEvent;
}
}
};
//CRUD operations on Calendar starts here
var modal = $uibModal.open($scope.option);
modal.result.then(function (data) {
$scope.NewEvent = data.event;
switch (data.operation) {
case 'Save': //save
$http({
method: 'POST',
url: '/Test/SaveEvent',
data: $scope.NewEvent
}).then(function (response) {
if (response.data.status) {
populate();
}
})
break;
case 'Delete': //delete
$http({
method: 'POST',
url: '/Test/DeleteEvent',
data: { 'eventID': $scope.NewEvent.EventID }
}).then(function (response) {
if (response.data.status) {
populate();
}
})
break;
default:
break;
}
}, function () {
console.log('Modal dialog closed');
})
}
}])
app.controller('modalController', ['$scope', '$uibModalInstance', 'NewEvent', function ($scope, $uibModalInstance, NewEvent) {
$scope.NewEvent = NewEvent;
$scope.Message = "";
$scope.ok = function () {
if ($scope.NewEvent.Title.trim() != "") {
$uibModalInstance.close({ event: $scope.NewEvent, operation: 'Save' });
}
else {
$scope.Message = "Event title required!";
}
}
$scope.delete = function () {
$uibModalInstance.close({ event: $scope.NewEvent, operation: 'Delete' });
}
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
}
}])
</script>
Update 2 (still the same thing):
<script>
var app = angular.module('myapp', ['ui.calendar', 'ui.bootstrap']);
app.controller('CalenderController', ['$scope', '$http', 'uiCalendarConfig', '$uibModal', function ($scope, $http, uiCalendarConfig, $uibModal) {
$scope.SelectedEvent = null;
var isFirstTime = true;
$scope.events = [];
$scope.eventSources = [$scope.events];
$scope.NewEvent = {};
//this function for get datetime from json date
function getDate(datetime) {
if (datetime != null) {
var mili = datetime.replace(/\/Date\((-?\d+)\)\//, '$1');
return new Date(parseInt(mili));
}
else {
return "";
}
}
//Test refresh events in calendar
/////////////////////////////////////////////////////////////////////////
function refreshCalendar() {
clearEvents();
clearCalendar();
//$timeout(function () {
// uiCalendarConfig.calendars.myCalendar.fullCalendar('rerenderEvents');
//});
//uiCalendarConfig.calendars.myCalendar.fullCalendar('removeEvents');
//uiCalendarConfig.calendars.myCalendar.fullCalendar('addEventSource', events);
//$scope.events.fullCalendar('refetchEvents');
uiCalendarConfig.calendars.myCalendar.fullCalendar('refetchEvents');
//uiCalendarConfig.calendars['myCalendar'].fullCalendar('refetchEvents');
//$scope.myCalendar.fullCalendar('refetchEvents');
//uiCalendarConfig.calendars.myCalendar.fullCalendar('refreshEvents');
//$scope.calendar.fullCalendar('refetchEvents');
//window.calendar.fullCalendar('referchEvents');
}
function clearEvents() {
uiCalendarConfig.calendars.myCalendar.fullCalendar('removeEvents');
}
// this function clears clender enents
function clearCalendar() {
if (uiCalendarConfig.calendars.myCalendar != null) {
uiCalendarConfig.calendars.myCalendar.fullCalendar('removeEvents');
//uiCalendarConfig.calendars.myCalendar.fullCalendar('refresh');
uiCalendarConfig.calendars.myCalendar.fullCalendar('unselect');
}
}
//Load events from server to display on caledar
function populate() {
clearCalendar();
//debugger;
$http.get('/Test/GetEvents', {
cache: false,
params: {}
}).then(function (data) {
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function (value) {
$scope.events.push({
id: value.EventID,
title: value.Title,
description: value.Description,
start: new Date(parseInt(value.StartAt.substr(6))),
end: new Date(parseInt(value.EndAt.substr(6))),
allDay: value.IsFullDay,
stick: true
});
});
});
}
populate();
//UI- calendar configuration
$scope.uiConfig = {
calendar: {
//height: 450,
height: 650,
editable: true,
displayEventTime: true,
header: {
left: 'month,agendaWeek,agendaDay',
center: 'title',
right: 'today prev,next'
},
timeFormat: {
month: ' ', // for hide on month view
agenda: 'h:mm t'
},
selectable: true,
selectHelper: true,
select: function (start, end) {
var fromDate = moment(start).format('YYYY/MM/DD LT');
var endDate = moment(end).format('YYYY/MM/DD LT');
$scope.NewEvent = {
EventID: 0,
StartAt: fromDate,
EndAt: endDate,
IsFullDay: false,
Title: '',
Description: ''
}
$scope.ShowModal();
},
eventClick: function (event) {
$scope.SelectedEvent = event;
var fromDate = moment(event.start).format('YYYY/MM/DD LT');
var endDate = moment(event.end).format('YYYY/MM/DD LT');
$scope.NewEvent = {
EventID: event.id,
StartAt: fromDate,
EndAt: endDate,
IsFullDay: false,
Title: event.title,
Description: event.description
}
$scope.ShowModal();
},
eventAfterAllRender: function () {
if ($scope.events.length > 0 && isFirstTime) {
uiCalendarConfig.calendars.myCalendar.fullCalendar('gotoDate', $scope.events[0].start);
isFirstTime = false;
}
}
}
};
//This function shows bootstrap modal dialog
$scope.ShowModal = function () {
$scope.option = {
templateUrl: 'modalContent.html',
controller: 'modalController',
backdrop: 'static',
resolve: {
NewEvent: function () {
return $scope.NewEvent;
}
}
};
//CRUD operations on Calendar starts here
var modal = $uibModal.open($scope.option);
modal.result.then(function (data) {
$scope.NewEvent = data.event;
//debugger;
switch (data.operation) {
case 'Save': //save
$http({
method: 'POST',
url: '/Test/SaveEvent',
data: $scope.NewEvent
}).then(function (response) {
if (response.data.status) {
populate();
refreshCalendar();
// //$scope.calendar.fullCalendar('render');
// //$scope.calendar.fullCalendar('refetchEvents');
}
})
break;
case 'Delete': //delete
$http({
method: 'POST',
url: '/Test/DeleteEvent',
data: { 'eventID': $scope.NewEvent.EventID }
}).then(function (response) {
if (response.data.status) {
populate();
}
})
break;
default:
break;
}
}, function () {
console.log('Modal dialog closed');
})
}
}])
app.controller('modalController', ['$scope', '$uibModalInstance', 'NewEvent', function ($scope, $uibModalInstance, NewEvent) {
$scope.NewEvent = NewEvent;
$scope.Message = "";
$scope.ok = function () {
if ($scope.NewEvent.Title.trim() != "") {
$uibModalInstance.close({ event: $scope.NewEvent, operation: 'Save' });
}
else {
$scope.Message = "Event title required!";
}
}
$scope.delete = function () {
$uibModalInstance.close({ event: $scope.NewEvent, operation: 'Delete' });
}
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
}
}])
</script>
Also followed this tutorial: http://www.dotnetawesome.com/2016/05/part-2-crud-operation-on-fullcalender.html, but with the same issue.
Found out what was wrong with it - doesn't entirely support IE.
Call RefreshCalendar() function on INSERT/UPDATE/DELETE event
function RefreshCalendar() {
ClearEvents();
$('#calendar').fullCalendar('refetchEvents');
}
function ClearEvents() {
$('#calendar').fullCalendar('removeEvents');
}
I have my angularApp written
var app = angular.module('flapperNews', ['ui.router']);
app.factory('posts', ['$http',function($http) {
var posts = [
{ title: 'post 1', upvotes: 5 },
{ title: 'post 2', upvotes: 2 },
{ title: 'post 3', upvotes: 15 },
{ title: 'post 4', upvotes: 9 },
{ title: 'post 5', upvotes: 4 }
];
var service = {};
service.getAll = function() {
return $http.get('/posts').success(function(data){
angular.copy(data, posts);
});
};
service.create = function(post) {
return $http.post('/posts', post).success(function(data){
posts.push(data);
});
};
service.getPosts = function() {
return posts;
};
service.upvote = function(post) {
return $http.put('/posts/' + post._id + '/upvote').success(function(data){
post.upvotes += 1;
});
};
service.get = function(id) {
return $http.get('/posts/'+id).then(function(res) {
return res.data;
});
}
return service;
}]);
app.controller('MainCtrl', ['$scope', 'postPromise',
function($scope, postPromise) {
$scope.posts = postPromise;
$scope.title = null;
$scope.link = null;
$scope.test = "Hello World";
$scope.addPost = function() {
if (!$scope.title || $scope.title === '') {
return;
} else {
posts.create({
title: $scope.title,
link: $scope.link,
});
$scope.link = '';
$scope.title = '';
}
};
$scope.incrementUpvotes = function(post) {
posts.upvote(post);
};
}
]);
app.controller('PostsCtrl', [
'$scope',
'posts',
'post',
function($scope, posts, post) {
$scope.post = post;
$scope.addComment = function(){
if($scope.body === '') { return; }
$scope.post.comments.push({
body: $scope.body,
author: 'user',
upvotes: 0
});
$scope.body = '';
};
}
]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function(posts){
return posts.getAll();
}]
}
})
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'PostsCtrl',
resolve: {
post: ['$stateParams', 'posts', function($stateParams, posts) {
return posts.get($stateParams.id);
}]
}
});
$urlRouterProvider.otherwise('home');
}
]);
When I load the Homepage I get an error saying
Unknown provider: postPromiseProvider <- postPromise <- MainCtrl
I do not understand this.
I have tried restructuring the code, placing the factory above the Controllers, but it still throws the same error.
PS - The network call to retrieve posts is made (I can see it in the Browser Netwrok calls)
The name of your factory is posts not postPromise.
Change your MainCtrl to:
app.controller('MainCtrl', ['$scope', 'posts', function($scope, posts) {
});
I'm new to using the MEAN stack, have learned some of the basics to add data to mongodb using mongoose, express, and ui-router. However, I can't figure out how to delete a document. Whenever I try, I get 404 errors, even though it looks like the link should be correct. Would someone please help? Be kind, my code might be way off...
Here is my angular file:
var app = angular.module('updateTracker', ['ui.router']);
app.factory('courses', ['$http', function($http){
var o = {
courses: []
};
o.getAll = function() {
return $http.get('/courses').success(function(data){
angular.copy(data, o.courses);
});
};
o.create = function(course) {
return $http.post('/courses', course).success(function(data){
o.courses.push(data);
});
};
o.get = function(id) {
return $http.get('/courses/' + id).then(function(res){
return res.data;
});
};
o.addEntry = function(id, entry) {
return $http.post('/courses/' + id + '/entries', entry);
};
o.changeLesson = function(course) {
return $http.put('/courses/' + course._id + '/changeLesson')
.success(function(data){
course.lesson = "New Lesson";
});
};
o.removeCourse = function(course) {
return $http.delete('/courses/' + course._id + '/removeCourse')
.success(function (data, status) {
console.log(data);
});
};
return o;
}]);
app.controller('MainCtrl', [
'$scope',
'courses',
function($scope, courses){
$scope.courses = courses.courses;
$scope.addCourse = function(){
if(!$scope.lesson || $scope.lesson === '') { return; }
courses.create({
lesson: $scope.lesson,
course: $scope.course,
curriculum: $scope.curriculum
});
$scope.lesson = '';
$scope.course = '';
$scope.curriculum = '';
};
$scope.changeLesson = function(course){
courses.changeLesson(course);
};
$scope.removeCourse = function(course) {
courses.removeCourse(course);
};
}]);
app.controller('CoursesCtrl', [
'$scope',
'courses',
'course',
function($scope, courses, course){
$scope.course = course;
$scope.addEntry = function(){
// if($scope.version === '') { return; }
courses.addEntry(course._id, {
version: $scope.version,
notes: $scope.notes,
statusCode: $scope.statusCode,
statusMessage: $scope.statusMessage,
author: 'user'
}).success(function(entry) {
$scope.course.entries.push(entry);
});
$scope.version = '';
$scope.notes = '';
$scope.statusCode = '';
$scope.statusMessage = '';
};
}]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['courses', function(courses){
return courses.getAll();
}]
}
})
.state('courses', {
url: '/courses/{id}',
templateUrl: '/courses.html',
controller: 'CoursesCtrl',
resolve: {
course: ['$stateParams', 'courses', function($stateParams, courses) {
return courses.get($stateParams.id);
}]
}
});
$urlRouterProvider.otherwise('home')
}]);
My routes:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Course = mongoose.model('Course');
var Entry = mongoose.model('Entry');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
router.get('/courses', function(req, res, next) {
Course.find(function(err, courses) {
if(err){ return next(err); }
res.json(courses);
});
});
router.post('/courses', function(req, res, next) {
var course = new Course(req.body);
course.save(function(err, course) {
if(err){return next(err); }
res.json(course);
});
});
router.param('course', function(req, res, next, id) {
var query = Course.findById(id);
query.exec(function (err, course){
if (err) { return next(err); }
if (!course) { return next(new Error('can\'t find course')); }
req.course = course;
return next();
});
});
router.get('/courses/:course', function(req, res, next) {
req.course.populate('entries', function(err, course) {
if (err) { return next(err); }
res.json(course);
});
});
router.post('/courses/:course/entries', function(req, res, next) {
var entry = new Entry(req.body);
entry.course = req.course;
entry.save(function(err, entry){
if(err){ return next(err); }
req.course.entries.push(entry);
req.course.save(function(err, course) {
if(err){ return next(err); }
res.json(entry);
});
});
});
router.put('/courses/:course/changeLesson', function(req, res, next) {
req.course.changeLesson(function(err, course){
if (err) { return next(err); }
res.json(course);
});
});
router.delete('courses/:course', function(req, res) {
Course.remove({
_id : mongodb.ObjectID(req.params.course)
}, function(err) {
if(err) { res.send(err);}
console.log("remove id");
})
});
router.param('entry', function(req, res, next, id) {
var query = Entry.findById(id);
query.exec(function (err, entry){
if (err) { return next(err); }
if (!entry) { return next(new Error('can\'t find entry')); }
req.entry = entry;
return next();
});
});
and my course Schema:
var mongoose = require('mongoose');
var CourseSchema = new mongoose.Schema({
lesson: String,
course: String,
curriculum: String,
entries: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Entry'}]
});
CourseSchema.methods.changeLesson = function(cb) {
this.lesson = "Update Lesson";
this.save(cb);
};
mongoose.model('Course', CourseSchema);
You forgot to add / in the begining of router.delete and /removeCourse at end as well as did not return value using either res.send or res.json or res.end, etc. This should be like bellow
router.delete('/courses/:course/removeCourse', function(req, res) {
Course.remove({
_id : req.params.course
}, function(err) {
if(err) {
console.log(err);
res.status(500).send(err);
} else {
res.json({});
console.log("remove id");
}
})
});
factory:
angular.module('clientApp').factory('Di', function($http) {
return {
create: function(dis){
return $http.post('/dis', dis);
}
});
Controller:
'use strict';
angular.module('clientApp').controller('AdminCtrl', function($scope, toastr, Di) {
$scope.di = {};
$scope.dis = [];
$scope.add = function(){
Di.create($scope.di).then(function(response){
console.log(response, 'front data post')
$scope.dis.push(response.data);
$scope.di= {};
});
};
});
When I console.log() the response, the only thing I see in response.data is the hashKey. I do see the object in response.config.data, but from what I've seen online, this is just the original object i'm sending to the database, not the returned promise, right?
The data is saving to the database.
What am I doing wrong? I've done a similar configuration successfully with other promises, but the response is not what I'm expecting here.
API
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var DiSchema = new mongoose.Schema({
name: { type: String, lowercase: true , required: true },
photo: { type: String },
email: { type: String, unique: true, lowercase: true },
year: { type: Number},
timestamp: { type : Date, default: Date.now },
description: { type: String},
location: { type: Array },
social: {
website: {type: String},
facebook: {type: String },
twitter: {type: String },
instagram: {type: String }
}
});
DiSchema.methods.create = function(o, cb){
this.model.save(o, cb);
};
module.exports = mongoose.model('Di', DiSchema);
controller:
'use strict';
var Di = require('../models/di');
exports.create = function(req, res){
Di.create(req.body , user, function(err, di){
console.log('req.body.di', req.body);
res.send({di:di});
});
};
Routes:
var dis = require('../contollers/dis');
app.post('/dis', dis.create);
You had a typo with an extra parameter within your create function.
exports.create = function(req, res){
Di.create(req.body , function(err, di){
console.log('req.body.di', req.body);
res.send({di:di});
});
};
I think you should bind your promise to the scope.
Would that fix the problem? Can you try?
$scope.add = function(){
Di.create($scope.di).then(function(response){
console.log(response, 'front data post')
$scope.dis.push(response.data);
$scope.di= {};
}.bind($scope));
};
I have a service class in angular that calls my backend and gets a userInfo as an object. My angular service class has the following.
var userResource = $resource(coreURL+'getFullProfile', {}, {
getUserInfo: {
method: 'POST'
}
userService.getUserInfo = function (userObj) {
var res = userResource.getUserInfo();
var promises = res.$promise;
return promises;
}
My controller class has the following.
promise = userService.getUserInfo();
promise.then(function (response) {
$scope.user = response;
});
My backends service returns an object.
My problem is I get the user info Object from backend but its not properly wrapped inside a object.the object is mix up with some angular variables. I dont have a response.data .the response object itself has all the information.
$promise: Objectcatch: function (callback) {finally: function (callback) {then: function (callback, errback, progressback) {__proto__:
Object
$resolved: true
about: "sdadsf"
country: "India"
creationDate: "2015-04-07"
email: "user3"
id: 3
industries: Array[2]
name: "user3"
phoneNo: 0
progressLevel: 1
The above response contains $promise and $resolved combined in my object. how can I get my data separately as an object.
controller.js
(function () {
var userController;
userController = function ($scope, userService, searchService) {
var delegate;
var masterUser;
$scope.user = {};
$scope.newEducation = [];
$scope.newProfession = [];
$scope.editMode=false;
$scope.hospitals=[];
$scope.yearOptions={
'year-format': "'yy'",
'starting-day': 1,
'datepicker-mode':"'year'",
'min-mode':"year"
};
$scope.hospit=function(){
promise = userService.getHospitals();
promise.then(function (response) {
$scope.hospitals = response.data;
});
};
delegate = {
getUserInfo: function () {
userService.getUserInfo(this.onGetUserData,this.onGetError);
},
onGetUserData :function(data){
var usr = (new dcuser(data));
$scope.user = usr;
$scope.masterUser = angular.copy(usr);
},
onGetError :function(data){
alert("error");
},
saveUserInfo:function(){
alert('saveUserInfo');
userService.saveUserInfo($scope.user,this.onSaved);
},
onSaved:function(){
$scope.editMode=false;
},
enableEdit:function(){
$scope.editMode = true;
},
cancelEdit:function(){
angular.copy($scope.masterUser, $scope.user);
$scope.editMode = false;
delegate.getUserInfo();
},
getIndustries :function(){
alert("getIndustries");
},
searchHospitals :function(){
searchService.searchHospitals("a",this.onGetHospitals);
},
onGetHospitals :function(data){
$scope.hospitals = data;
},
searchMedicalSchools :function(){
searchService.searchMedicalSchools("a",this.onGetMedicalSchools);
},
onGetMedicalSchools :function(data){
$scope.medicalSchools = data;
},
connectUser:function(user){
alert("connectUser");
userService.connectUser(user,this.onConnectSuccess,this.onGetError);
},
onConnectSuccess:function(){
alert("connection request sent");
},
initProfieCompletion: function(){
alert("in");
$scope.user.profession = [];
$scope.user.profession.push({
"hospital": "as",
"speciality": "as",
"fromDate": "",
"toDate": ""
});
promise = userService.getHospitals();
promise.then(function (response) {
$scope.hospitals = response.data;
});
},
addEducation:function(){
$scope.newEducation.push({
"medicalSchool": "",
"speciality": "",
"degree": "",
"graduatedYear": ""
});
},
addProfession:function(){
$scope.newProfession.push({
"hospital": "",
"speciality": "",
"fromDate": "",
"toDate": ""
});
}
};
return $scope.delegate = delegate;
}
dc.userModule.controller('userController', userController);
}).call(this);
service.js
(function () {
"use strict";
dc.app.service('userService', ['$rootScope','$resource', '$http', function ($rootScope,$resource, $http) {
var userService = {};
var coreURL = $rootScope.coreURI+'user/';
var userResource = $resource(coreURL+'getFullProfile', {}, {
getUserInfo: {
method: 'GET'
},
saveUserInfo: {
method: 'POST',
url: coreURL+'updateUserInfo'
}
});
var connectResource = $resource(coreURL + 'connectRequest',{}, {
connectUser: {
method: 'POST'
}
});
var userPhotoResource = $resource(coreURL + 'uploadPhoto', {}, {
uploadPhoto: {
method: 'POST'
}
});
userService.getUserInfo = function (onSuccess,onFailure) {
return(userResource.getUserInfo(onSuccess,onFailure));
},
userService.saveUserInfo = function(user,onSuccess){
return userResource.saveUserInfo(user,onSuccess);
},
userService.connectUser = function(user,onSuccess,onFailure){
return connectResource.connectUser(user,onSuccess,onFailure);
},
userService.uploadPhoto =function(image){
var promises = userPhotoResource.uploadPhoto(image);
return promises;
},
userService.getHospitals = function(){
alert('ser');
var promises = $http.get('dcResources/hospitals.json');
return promises;
}
return userService;
}]);
}).call(this);