I am using angular js and I have a get method '$scope.getAllEmployeesList'. In this method I put the response data into the '$scope.employeeList'. However, list contains data only inside the method but it become empty outside the get method.
Here is my code:
var app = angular.module('app', []);
app.controller('basicInfoController', function ($scope, $http, $location) {
$scope.submitForm = function () {
var url = "http://localhost:8080/basicInfo/save";
var data = {
employeeId: $scope.employeeId,
firstName: $scope.firstName,
lastName: $scope.lastName,
companyId: $scope.companyId,
phoneNo: $scope.phoneNo,
sexId: $scope.sexId,
sexName: $scope.sexName,
birthDate: $scope.birthDate,
joiningDate: $scope.joiningDate,
department: $scope.department
};
$http.post(url, data).then(function (response) {
$scope.postResultMessage = "Sucessful!";
$scope.successMessage = 'User created successfully';
}, function (response) {
$scope.postResultMessage = "Fail!";
});
$scope.employeeId = "";
$scope.firstName = "";
$scope.lastName = "";
$scope.companyId = "";
$scope.phoneNo = "";
$scope.sexId = "";
$scope.sexName = "";
$scope.birthDate = "";
$scope.joiningDate = "";
$scope.department = "";
}
$scope.employeeList =[];
$scope.getAllEmployeesList = function () {
var url = $location.absUrl() + "basicInfo/getAllEmployeeBasicInfo";
var config = {
headers: {
'Content-Type': 'application/json;charset=utf-8;'
}
}
$http.get(url, config).then(function (response) {
$scope.employeeList = response.data;
$scope.employeeList = angular.copy(response.data);
console.log($scope.employeeList);
}, function (response) {
$scope.getResultMessage = "Fail!";
});
}
$scope.getAllEmployeesList();
console.log($scope.employeeList);
function reset() {
$scope.basicInfo = {
employeeId: '',
firstName: '',
lastName: '',
phoneNo: '',
sex: '',
birthDate: '',
companyId: '',
department: '',
joiningDate: ''
};
$scope.myForm.$setPristine(); //reset Form
}
});
in $scope.getAllEmployeesList method, when I print 'console.log($scope.employeeList);' inside the method then it is showing value but if print out side the method then empty list is shown.
Just return the $http... then tack on another .then().
var app = angular.module('app', [])
.controller('basicInfoController', function ($scope, $http, $location) {
function submitForm() {
var url = "http://localhost:8080/basicInfo/save";
var data = {
employeeId: $scope.employeeId,
firstName: $scope.firstName,
lastName: $scope.lastName,
companyId: $scope.companyId,
phoneNo: $scope.phoneNo,
sexId: $scope.sexId,
sexName: $scope.sexName,
birthDate: $scope.birthDate,
joiningDate: $scope.joiningDate,
department: $scope.department
};
$http.post(url, data).then(function() {
$scope.postResultMessage = "Sucessful!";
$scope.successMessage = 'User created successfully';
}, function() {
$scope.postResultMessage = "Fail!";
});
$scope.employeeId = "";
$scope.firstName = "";
$scope.lastName = "";
$scope.companyId = "";
$scope.phoneNo = "";
$scope.sexId = "";
$scope.sexName = "";
$scope.birthDate = "";
$scope.joiningDate = "";
$scope.department = "";
}
$scope.employeeList = [];
function getAllEmployeesList() {
var url = $location.absUrl() + "basicInfo/getAllEmployeeBasicInfo";
var config = {
headers: {
'Content-Type': 'application/json;charset=utf-8;'
}
}
return $http.get(url, config).then(function() {
$scope.employeeList = response.data;
$scope.employeeList = angular.copy(response.data);
}, function() {
$scope.getResultMessage = "Fail!";
});
}
getAllEmployeesList().then(function() {
console.log($scope.employeeList);
});
function reset() {
$scope.basicInfo = {
employeeId: '',
firstName: '',
lastName: '',
phoneNo: '',
sex: '',
birthDate: '',
companyId: '',
department: '',
joiningDate: ''
};
$scope.myForm.$setPristine(); //reset Form
}
$scope.getAllEmployeesList = getAllEmployeesList;
$scope.submitForm = submitForm;
});
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');
}
Hello everyone am trying to search (query) the mongodb using mongoose in my AngularJS app. Am looking to have specific element. Can you help ? Any suggestion would make me advance. I need the general idea. Also I am new to mean
here is my angular code :
var app = angular.module('chirpApp', ['ngRoute', 'ngResource']).run(function($rootScope, $http) {
$rootScope.authenticated = false;
$rootScope.current_user = '';
$rootScope.signout = function(){
$http.get('auth/signout');
$rootScope.authenticated = false;
$rootScope.current_user = '';
};
});
app.config(function($routeProvider){
$routeProvider
//the timeline display
.when('/', {
templateUrl: 'main.html',
controller: 'mainController'
})
//the login display
.when('/login', {
templateUrl: 'login.html',
controller: 'authController'
})
//the signup display
.when('/register', {
templateUrl: 'register.html',
controller: 'authController'
})
//search
.when('/search', {
templateUrl: 'search.html',
controller: 'searchController'
});
});
app.factory('postService', function($resource){
return $resource('/api/posts/:id');
});
app.controller('mainController', function(postService, $scope, $rootScope){
$scope.posts = postService.query();
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function() {
$scope.newPost.created_by = $rootScope.current_user;
$scope.newPost.created_at = Date.now();
postService.save($scope.newPost, function(){
$scope.posts = postService.query();
$scope.newPost = {created_by: '', text: '', created_at: ''};
});
};
});
app.controller('searchController', function(postService, $scope, $rootScope){
$scope.posts = [];
$scope.posts = postService.get(text:"1223");
$scope.tiks=[];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function() {
$scope.newPost.created_by = $rootScope.current_user;
$scope.newPost.created_at = Date.now();
postService.save($scope.newPost, function(){
$scope.posts = postService.query();
$scope.newPost = {created_by: '', text: '', created_at: ''};
});
};
});
app.controller('authController', function($scope, $http, $rootScope, $location){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
$http.post('/auth/login', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
$scope.register = function(){
$http.post('/auth/signup', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
});
in the searchController am trying to query a specific post with text 123.
Here is my schema :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var postSchema = new mongoose.Schema({
username: { type: Schema.ObjectId, ref: 'User' },
created_at: {type: Date, default: Date.now},
text: String
});
var userSchema = new mongoose.Schema({
username: String,
password: String, //hash created from password
created_at: {type: Date, default: Date.now}
})
mongoose.model('Post', postSchema);
mongoose.model('User', userSchema);
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, { ...
I am trying to develop a simple form using angular js 1.* and asp.net mvc 5. When I try to save the form data using $http(), it hits the action but none of the data is passed. But if I use $.post(), it works perfectly.
Could anybody please explain me why? Is that because we need to use ApiController instead of normal mvc's Controller? Or what could be the potential problem?
AddEmployeeController.js
(function () {
'use strict';
angular.module('ApplicationModule').controller('AddEmployeeController', function ($scope, SPACRUDService) {
$scope.Id = 0;
$scope.employee = {
FirstName: 'Hello',
MiddleName: '',
LastName: '',
CurrentAddress: '',
PermanentAddress: '',
Gender: 'M',
MobilePhone: '',
HomePhone: '',
Email: '',
CitizenshipNumber: '',
FatherName: 'n/a',
DOB: '',
TaxID: '',
EmergencyFullName: '',
EmergencyRelationship: '',
EmergencyPhoneNo: '',
EmergencyMobileNo: '',
IsCitizenshipCertProvided: false,
IsAcademicCertProvided: false,
IsExpOrReferenceLetterProvided: false
};
$scope.save = function () {
var Employee = $scope.employee;
var promisePost = SPACRUDService.post(Employee);
promisePost.then(function (data) {
alert("Saved Sucessfully!");
},
function (error) {
$scope.error = "Failed ", error;
}
);
};
});
AddEmployeeController.$inject = ['$location'];
function AddEmployeeController($location) {
/* jshint validthis:true */
var vm = this;
vm.title = 'AddEmployeeController';
activate();
function activate() { }
} })();
Service.js
(function () {
'use strict';
angular.module('ApplicationModule').service("SPACRUDService", function ($http) {
//gets all employees
this.getEmployees = function () {
var request = $http({
method: "get",
url: "/Employee/GetAllEmployees",
});
return request;
}
//gets a employee by id
this.getEmployee = function (Id) {
var request = $http({
method: "get",
url: "/Employee/GetEmployeeById",
data: id
});
return request;
}
//creates a new employee
//this.post = function (Employee) {
// var request = $http({
// method: "post",
// url: "/Employee/Save",
// data: Employee
// });
// return request;
//}
//for creating a new employee
this.post = function (emp) {
// return $.post('/Employee/Save', emp); //this one works
return $http.post('/Employee/Save', emp); //this doesn't
}
//updates the chosen employee
this.put = function (Employee, Id) {
var request = $http({
method: "post",
url: "/Employee/Update",
data: { id: Id, employee: Employee }
});
return request;
}
//removes the employee
this.put = function (Id) {
var request = $http({
method: "post",
url: "/Employee/Delete",
data: id
});
return request;
}
}) })();
EmployeeController
[HttpPost]
public JsonResult Save(Employee emp)
{
db.Add(emp);
return Json(db.SaveChanges());
}
The new .net core mvc requires [FormBody] to be attached to the parameter if it is coming as Json Data. This behavior is from web api 2.
[HttpPost]
public JsonResult Save([FormBody]Employee emp)
{
db.Add(emp);
return Json(db.SaveChanges());
}
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);