Thinkster MEAN stack tutorial, deletion of element - angularjs

I've been following the Thinkster Mean Stack tutorial, and it works wonderfully. So I have created my own project, and so far everything works fine.
However, they didn't cover how to delete posts.
And I can for the life for me not figure out how to delete an element from the data.
AngularApp.js
var app = angular.module('KOL', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: "/views/home.ejs",
controller: 'kolCtrl',
resolve: {
patientPromise: ['patients', function(patients) {
return patients.getAll();
}]
}
})
.state('details', {
url: '/details/{id}',
templateUrl: './views/details.html',
controller: 'detailsCtrl'
});
$urlRouterProvider.otherwise('home');
}])
.factory('patients', ['$http', function($http){
var object = {
patients: []
};
object.getAll = function() {
return $http.get('/patients').success(function(data) {
angular.copy(data, object.patients);
});
}
object.create = function(patient) {
return $http.post('/patients', patient).success(function(data){
object.patients.push(data);
});
}
};
return object;
}])
.controller('kolCtrl', ['$scope', 'patients',
function($scope, patients){
$scope.patients = patients.patients;
$scope.selectedItem = $scope.patients[0];
$scope.addPost = function() {
if(!$scope.title || $scope.title === '') { return; }
if(!$scope.age || $scope.age === '') { return; }
patients.create({
name: $scope.title,
age: $scope.age,
})
$scope.title = '';
$scope.age = '';
};
object.delete = function(patient)
}])
.controller('detailsCtrl', [
'$scope',
'$stateParams',
'patients',
function($scope, $stateParams, patients){
$scope.patient = patients.patients[$stateParams.id];
}])
;
Home.ejs
<div class="container">
<div clas="row">
<div style="width: 200px; margin-top: 100px">
<select ng-model="selectedItem" ng-options="patients.name for patients in patients" class="pull-left form-control" name="Vælg"></select>
</div>
<div class="viewbox pull-right">
<h3>Patient: {{selectedItem.name}}</h3>
<p>Age: {{selectedItem.age}} </p>
<p>index: {{patients.indexOf(selectedItem)}}</p>
<button>Rediger</button>
<button ng-click="deleteItem(patients.indexOf(selectedItem))">Delete</button>
</div>
</div>
<div class="row" class="pull-left">
<div style="width: 200px; margin-top: 100px">
<form role="form" class="form-group" ng-submit="addPost()">
<input class="form-control" type="text" ng-model="title" />
<input class="form-control" type="text" ng-model="age" />
<button type="submit">Add</button>
</form>
</form>
</div>
</div>
</div>
index.js (route get and post)
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
var mongoose = require('mongoose');
var Patient = mongoose.model('Patient');
router.get('/patients', function(req, res, next) {
Patient.find(function(err, patients){
if(err){ return next(err); }
res.json(patients);
});
});
router.post('/patients', function(req, res, next) {
var patient = new Patient(req.body);
patient.save(function(err, post){
if(err){ return next(err); }
res.json(patient);
});
});
router.delete('/patients/:patient', function(req, res, next) {
req.patient.remove(function(err, patient){
if (err) { return next(err); }
res.json(patient);
});
});
router.param('patient', function(req, res, next, id) {
var query = Patient.findById(id);
query.exec(function (err, patient){
if (err) { return next(err); }
if (!post) { return next(new Error('can\'t find patient')); }
req.patient = patient;
return next();
});
});
router.get('/details/:patient', function(req, res) {
res.json(req.patient);
});
module.exports = router;
I suspect the answer is quite straightforward, given the other code, but maybe not?
Thanks.

According to your function that you are passing to the router.delete in your index.js file:
router.delete('/patients/:patient', function(req, res, next) {
req.patient.remove(function(err, patient){
if (err) { return next(err); }
res.json(patient);
});
});
You'll have to append the patients.id to the url when using the delete verb with the $http service. So you can add a delete method to the object in your patients factory:
.factory('patients', ['$http', function($http){
var object = {
patients: []
};
object.getAll = function() {
return $http.get('/patients').success(function(data) {
angular.copy(data, object.patients);
});
}
object.create = function(patient) {
return $http.post('/patients', patient).success(function(data){
object.patients.push(data);
});
}
//add patient id to the url
object.delete = function(patient) {
return $http.delete('/patients/',patient).success(function(data){
console.log(data);
});
}
}
};
return object;
}])

object.delete = function(patient) {
return $http.delete('/patients', patient).success(function(data){
for(var i = 0; i < object.patients.length; i++) {
if(object.patients[i].id == patient.id) {
object.patients.splice(i, 1);
}
});
Something like that maybe, hard to say without knowing the response. If the response (data) is the deleted patient then you can use "if(object.patients[i].id == data.id)" instead

Related

Scope from controller does not pass to directive

I have a html like this :
<div id="create-group" ng-controller="groupCreateController">
<div id="container">
<h1>Create group</h1>
<div class="row">
<div class="col-md-4"><input placeholder="Group Name.." ng-model="group.name"></div>
<div class="col-md-8">
<label>Group Description : </label>
<textarea ng-model="group.description"> </textarea>
</div>
</div>
<br/>
<div class="row">
<div class="col-sm-6">
<usermgr-permission-list group="group"></usermgr-permission-list>
<button type="button" class="btn btn-md btn-primary" ng-click="btnSave_click($event)">SAVE</button>
</div>
<div class="col-sm-6">
<usermgr-user-list group="group"></usermgr-user-list>
</div>
</div>
</div>
</div>
My controller is :
(function (module) {
'use strict';
module.controller('groupCreateController', function ($scope, $rootScope, $routeParams, $location, userGroupService, $mdDialog) {
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group[0].id = info.id;
$scope.group[0].name = info.name;
$scope.group[0].description = info.description;
console.log($scope.group);
// $rootScope.$broadcast('rCube-user-mgt-users-list', info.id);
// $rootScope.$broadcast('rCube-user-mgt-permissions-list', info.id);
}
else {
}
}).catch(function (exception) {
console.error(exception);
});
}
$scope.init();
});
})(angular.module('r-cube-user-mgt.user-group'));
I have two custom directives in the first block of code for user permissions and users. The group scope that i pass with the directive does not contain the values i put in the getUserGroup(id) function. The group name and group description shows up so the scope.group in the controller is filled, however thats not the case once i pass it to my directives. here is the directives code as well :
permissions list :
(function (module) {
'use strict';
module.directive('usermgrPermissionList', function () {
return {
restrict: 'E',
scope:{
group: '='
},
controller: function ($scope, permissionService) {
$scope.updatedPermissions=[];
console.log($scope.group); //it doesnt have the values from the controller ..
if (!$scope.group.hasOwnProperty('permissions')) {
$scope.group.permissions = [];
}
function getData() {
console.log("inside getDAta for permission list" + $scope.group.id;
permissionService.getPermissionsFiltered($scope.group.id).then(function (info) {
if (info && info.length > 0) {
console.log(info);
$scope.group.permissions = info.map(function (a, index, array) {
return {
id: a.id,
name: a.name,
description: a.description,
assigned: a.assigned
};
});
}
}).catch(function (exception) {
console.error(exception);
});
} //end of getData()
$scope.init = function () {
getData();
};
$scope.init();
},
templateUrl: 'r-cube-user-mgt/permission/list/list.tpl.html'
};
});
})(angular.module('r-cube-user-mgt.permission'));
can anyone help?
you cannot assign property to an array like this $scope.group.id = 0;
either make $scope.group object
$scope.group = {};
or add properties to an index
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
So I solved the issue by adding broadcast to send the id when the directive loads. This worked!
in the Group controller i add broadcast and send the group.id
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group.id = info.id;
$scope.group.name = info.name;
$scope.group.description = info.description;
console.log($scope.group);
$rootScope.$broadcast(rCubeTopics.userMgtPermissionLoadData, $scope.group.id);
}
}).catch(function (exception) {
console.error(exception);
});
}
and in the permission directive get that broadcast :
$scope.$on(rCubeTopics.userMgtPermissionLoadData, function (event, id) {
console.log($scope.group.id);
getData();
});

how to implement ng-model value from another view in ionic

I want to display ng-model value from page to input in another page
I Want display selected issue from issues page to contact page
Issue Controller
.controller('IssueCtrl', function($scope, $http) {
$http.get('api/issues').then(function(resp) {
console.log('Success', resp);
$scope.issues = resp.data;
}, function(err) {
console.error('ERR', err);
$scope.issues = err;
});
})
Contact Controller
.factory('Post', function($resource) {
return $resource('api/add_new_order',{problem: "#problem"});
})
.controller('ContactCtrl', function($scope, Post) {
// Get all posts
$scope.posts = Post.query();
// Our form data for creating a new post with ng-model
$scope.postData = {};
$scope.newPost = function() {
var post = new Post($scope.postData);
post.$save();
}
$scope.issues = {};
$scope.answer = function(){
console.log($scope.issues.name);
}
})
Issue View
<ion-list ng-repeat="item in issues">
<ion-radio ng-model="issues.name" ng-value="'{{item.issue}}'">
{{item.issue}}
</ion-radio>
</ion-list>
Contact View
<form ng-submit="newPost()">
<label class="item item-input">
<span class="input-label">Problem :</span>
<input type="text" name="problem" ng-model="postData.problem">
</label>
</form>
Your API requests should be on independent services, so they can be accessed by any controller.
As you seen to know how a factory works, I will give you an example.
.factory('IssuesService', function($http) {
var issues = [];
return {
all: function() {
return $http.get('api/issues')
.then(function(data){ // Optional callback inside service
issues = data;
});
}
}
})
.controller('ContactCtrl', function($scope, Post, IssuesService) {
...
$scope.issues = [];
IssuesService.all().then(function(data){
$scope.issues = data;
})
...
})
.controller('IssueCtrl', function($scope, $http) {
IssuesService.all()
.then(function(resp) {
console.log('Success', resp);
$scope.issues = resp.data;
}, function(err) {
console.error('ERR', err);
$scope.issues = err;
});
})

How to save data values from form in angularjs using fat free framework

I am trying to save data in sql using fat free framework. i used front end in angularjs. i send data using angular ng-submit button. ajax Post data but not get in fat free please solve this problem. i am new in fat free.
here is my html code:
<form id="userRegister" name="registration" ng-submit="register1(formData)" ng-controller="Ctrl1">
<div class="sf-steps-form sf-radius">
<div class="sf_columns column_3">
<input ng-model="formData.email" id="email" type="email" name="email" placeholder="Email*" data-required="true" >
</div>
<div class="sf_columns column_3">
<input ng-model="formData.password" id="password" type="password" name="password" placeholder="Secret Word*" data-required="true" >
</div>
</div>
<button type="submit" id="sf-next" class="sf-button">Save</button>
</form>
here is my app.js code:
sampleApp.controller("Ctrl1", function($scope, $http) {
$scope.formData = {};
$scope.register1 = function() {
console.log($scope.formData);
$http({
method : 'POST',
url : 'addstep',
data : $scope.formData,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
$scope.errorEmail = data.errors.email;
$scope.errorPassword = data.errors.password;
} else {
$scope.message = data.message;
}
});
};
});
here is my idex.php fat free framework code:
$f3->route('GET|POST /addstep',
function($f3) {
//print_r($f3);
$users = new DB\SQL\Mapper($f3->get('DB'),'user');
$users->copyFrom('POST');
$users->save();
$f3->set('content','step1.htm');
echo View::instance()->render('layout.htm');
}
);
The ajax post data properly but not save in db please help.
Check $f3->get('BODY');
You might need to json_decode;
Most likely the data is sent via PUT
I actually just dealt with this on an application using f3 and angular. If you haven't figured it out I have been pretty successful with this:
I have an angular $http service:
angular.module('myApp')
.service('apiConnector', function apiConnector($http) {
var apiBase = '';
var obj = {};
obj.get = function(q) {
return $http.get(apiBase + q).then(function(results) {
return results.data;
});
};
obj.post = function(q, object) {
return $http.post(apiBase + q, object).then(function(results) {
return results.data;
});
};
obj.put = function(q, object) {
return $http.put(apiBase + q, object).then(function(results) {
return results.data;
});
};
obj.delete = function(q) {
return $http.delete(apiBase + q).then(function(results) {
return results.data;
});
};
return obj;
});
Then I use this service in my angular controllers like so:
angular.module('myApp')
.controller('homeController',function($scope, $state, $stateParams, $timeout, apiConnector){
$scope.user = {};
apiConnector.get('/api/users/'+$stateParams.id)
.then(function(res){
if (res.success) {
$scope.user = res.data;
}
},function(err){
console.log(err);
});
$scope.updateUser = function(user) {
apiConnector.post('/api/users/'+$stateParams.id,user)
.then(function(res){
if (res.success) {
alert('updated');
}
}, function(err){
console.log(err);
});
};
});
Lastly the f3 controller. I am using [maps] for my routes to get a truly restful interface, and my routes use an #id param. I collect data like so:
class Item {
function get($app,$params) {
$id = $params['id'];
$user = new \Models\User();
$user->load(array('id = ?',$id));
echo json_encode($user->cast());
}
function post($app,$params) {
$POST = json_decode(file_get_contents('php://input'));
$id = $params['id'];
$user = new \Models\User();
$user->load(array('id = ?',$id));
$user->copyfrom($POST);
$user->touch('created');
$user->save();
echo json_encode(array('message' => 'Successfully updated user!'));
}
function put() {}
function delete() {}
}
Hope that helps!

Rewrite from $http to $resource

I have the following code (from the book Angular-Up-And-Running):
angular.module('fifaApp')
.controller('TeamListCtrl', ['FifaService',
function(FifaService) {
var self = this;
self.teams = [];
FifaService.getTeams().then(function(resp) {
self.teams = resp.data;
});
}])
.factory('FifaService', ['$http',
function($http) {
return {
getTeams: function() {
return $http.get('/api/team');
},
getTeamDetails: function(code) {
return $http.get('/api/team/' + code);
}
}
}])
.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/team_list.html',
controller: 'TeamListCtrl as teamListCtrl'
});
});
And then on the server:
app.get('/api/team', function(req, res) {
res.send(FIFA.TEAMS_LIST);
});
I tried to rewrite it like this, to use $resource, but it does not show templateUrl views/team_list.html.
My solution:
angular.module('fifaApp','ngResource')
.controller('TeamListCtrl', ['FifaService',
function(FifaService) {
var self = this;
self.teams = [];
FifaService.query().$promise
.then(function(resp) {
self.teams = resp.data;
});
}])
//`$resource` now instead of `$http`
.factory('FifaService', ['$resource',
function($resource) {
return $resource('/api/team');
}])
.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/team_list.html',
controller: 'TeamListCtrl as teamListCtrl'
});
});
Why can't I see views/team_list.html?
Best Regards
<div class="team-list-container">
<div class="team"
ng-repeat="team in teamListCtrl.teams | orderBy: 'rank'">
<div class="team-info row">
<div class="col-lg-1 rank">
<span ng-bind="team.rank"></span>
</div>
<div class="col-sm-3">
<img ng-src="{{team.flagUrl}}" class="flag">
</div>
<div class="col-lg-6 name">
<a title="Image Courtesy: Wikipedia"
ng-href="#/team/{{team.code}}"
ng-bind="team.name"
style="color: cadetblue;"></a>
</div>
</div>
</div>
</div>
Try this.
FifaService.query()
.success(function(resp) {
self.teams = resp.data;
or remove the $promise and still use .then.
try something like this from here
angular.module('job.models', [])
.factory('Job', ['$resource', function($resource) {
var Job = $resource('/api/jobs/:jobId', { full: 'true', jobId: '#id' }, {
query: {
method: 'GET',
isArray: false,
transformResponse: function(data, header) {
var wrapped = angular.fromJson(data);
angular.forEach(wrapped.items, function(item, idx) {
wrapped.items[idx] = new Job(item);
});
return wrapped;
}
}
});
Job.prototype.getResult = function() {
if (this.status == 'complete') {
if (this.passed === null) return "Finished";
else if (this.passed === true) return "Pass";
else if (this.passed === false) return "Fail";
}
else return "Running";
};
return Job;
}]);

AngularJS show 2 models in one controller

I have 2 models(Project and Task) to show in my home.html, and I want my them to be displayed like this: http://plnkr.co/edit/ItNvBNBIrLxqwRrhye5p, where both scope of data is shown and filtered based on the same color.
I use an Angular controller (projectCtrl.js) to control data on my web page(home.html), and use an Angular service (projectService.js) to grab data from my api file (api.js) written with express framework and mongoose.
But my code doesn't show anything, so I have no idea what's wrong.
home.html:
<div class="row" ng-if="main.loggedIn">
<div ng-controller="ProjectController">
<div class="panel col-md-8">
<!-- Project heading setup -->
<div class="panel-group" ng-repeat="eachProject in project.projects | reverse track by $index">
<div class="panel panel-info">
<div class="panel-heading" data-toggle="collapse" ng-click="true" data-target="#projectDetails{{$index}}" href="#projectDetails{{$index}}">
<h4>{{eachProject.title}}: {{eachProject.short_description}}</h4>
</div>
<div class="panel-collapse collapse out" id="projectDetails{{$index}}">
<p class="panel-body">
<!-- Project detail table, where project data displays-->
<table class="table table-responsive table-bordered table-hover">
<tr>
<th>Description: </th>
<td>{{eachProject.description}}</td>
</tr>
</table>
<!-- Task heading setup -->
<div class="panel-group" ng-repeat="eachTask in task.tasks | filter: { projectID: eachProject.id }">
<div class="panel panel-success">
<div class="panel-heading" data-toggle="collapse" ng-click="true" data-target="#taskDetails{{$index}}" href="#taskDetails{{$index}}">
<h5>{{eachTask.title}}</h5>
</div>
<div class="panel-collapse collapse out" id="taskDetails{{$index}}">
<p class="panel-body">
<!-- Task detail table, where tasks data displays -->
<table class="table table-responsive table-bordered table-hover">
<tr>
<th>Description: </th>
<td>{{eachTask.description}}</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
ProjectCtrl.js
angular.module('projectCtrl', ['projectService'])
.controller('ProjectController', function(Project, Task, socketio) {
var vm = this;
Project.all()
.success(function(data) {
vm.projects = data;
})
vm.createProject = function() {
// Wrong due date prevention
var start = new Date(vm.projectData.start_date);
var due = new Date(vm.projectData.due_date);
if (start > due) {
alert("Due date can't be earlier than start date, please decide a new due date.");
return;
}
// Create project
vm.message = '';
Project.create(vm.projectData)
.success(function(data) {
// Clear up the project
vm.projectData = '';
vm.message = data.message;
$('#createProject').modal('hide');
})
}
Task.all()
.success(function(data) {
vm.tasks = data;
})
vm.createTask = function() {
// Wrong due date prevention
var start = new Date(vm.taskData.taskStart_date);
var due = new Date(vm.taskData.taskDue_date);
if (start > due) {
alert("Due date can't be earlier than start date, please decide a new due date.");
return;
}
// Create task
vm.message = '';
Task.create(vm.taskData)
.success(function(data) {
// Clear up the task
vm.taskData = '';
vm.message = data.message;
$('#createTask').modal('hide');
})
}
socketio.on('project', 'task', function(data) {
vm.projects.push(data);
vm.tasks.push(data);
})
})
.controller('AllProjectsController', function(projects, socketio) {
var vm = this;
vm.projects = projects.data;
socketio.on('project', function(data) {
vm.projects.push(data);
})
})
projectService.js
angular.module('projectService', [])
.factory('Project', function($http) {
var projectFactory = {};
projectFactory.create = function(projectData) {
return $http.post('/api', projectData);
}
projectFactory.allProjects = function() {
return $http.get('/api/all_projects');
}
projectFactory.all = function() {
return $http.get('/api');
}
projectFactory.deleteProject = function(id) {
return $http.post('/api/deleteProject', {id: id});
}
return projectFactory;
})
.factory('Task', function($http) {
var taskFactory = {};
taskFactory.create = function(taskData) {
return $http.post('/api', taskData);
}
taskFactory.allTasks = function() {
return $http.get('/api/all_tasks');
}
taskFactory.all = function() {
return $http.get('/api');
}
taskFactory.deleteTask = function(id) {
return $http.post('/api/deleteTask', {projectID: id});
}
return taskFactory;
})
.factory('socketio', function($rootScope) {
var socket = io.connect();
return {
on: function(eventName, callback) {
socket.on(eventName, function() {
var args = arguments;
$rootScope.$apply(function() {
callback.apply(socket, args);
})
})
},
emit: function(eventName, data, callback) {
socket.emit(eventName, data, function() {
var args = arguments;
$rootScope.apply(function() {
if(callback) {
callback.apply(socket, args);
}
})
})
}
}
})
api.js
var User = require('../models/user');
var Project = require('../models/project');
var config = require('../../config');
var secretKey = config.secretKey;
var jsonwebtoken = require('jsonwebtoken');
var fields = '...'; // a lot of fields, deleted them just to make it short
// Create tokens for users with jsonwebtoken
function createToken(user) {
var token = jsonwebtoken.sign({
id: user._id,
firstname: user.firstname,
lastname: user.lastname,
username: user.username
}, secretKey, {
expirtesInMinute: 1440
});
return token;
}
module.exports = function(app, express, io) {
var api = express.Router();
api.get('/all_projects', function(req, res) {
Project.find({}, function(err, projects) {
if (err) {
res.send(err);
return;
}
res.json(projects);
})
})
// login api
api.post('/login', function(req, res) {
User.findOne({
username: req.body.username
}).select(fields).exec(function(err, user) {
if(err) {
throw err;
}
if (!user) {
res.send({ message: "User doesn't exist"});
} else if(user){
var validPassword = user.comparePassword(req.body.password);
if (!validPassword) {
res.send({ message: "Invalid Password"});
} else {
var token = createToken(user);
res.json({
success: true,
message: "Login Successfully !",
token: token
});
}
}
});
});
//middleware
api.use(function(req, res, next) {
console.log("Somebody just logged in!");
var token = req.body.token || req.param('token') || req.headers['x-access-token'];
if (token) {
jsonwebtoken.verify(token, secretKey, function(err, decoded) {
if (err) {
res.status(403).send({success: false, message: "Failed to authenticate user."});
} else {
req.decoded = decoded;
next();
}
});
} else {
res.status(403).send({ success: false, message: "No Token Provided." });
}
});
//api for projects handling
api.route('/')
.post(function(req, res) {
var project = new Project({
creatorID: req.decoded.id,
creator: req.decoded.firstname + " " + req.decoded.lastname,
creator_dept: req.decoded.department,
title: req.body.title,
short_description: req.body.short_description,
description: req.body.description,
priority: req.body.priority,
status: calcStatus(),
assign_dept: req.body.assign_dept,
estimate_cost: req.body.estimate_cost,
actual_cost: req.body.actual_cost,
last_modified_date: req.body.last_modified_date,
due_date: req.body.due_date,
start_date: req.body.start_date,
complete_date: req.body.complete_date,
});
project.save(function(err, newProject) {
if (err) {
res.send(err);
return;
}
io.emit('project', newProject);
res.json({
message: "New Project Created!"
});
});
})
.get(function(req, res) {
Project.find( {creatorID: req.decoded.id}, function(err, project) {
if (err) {
res.send(err);
return;
}
res.json(project);
});
});
//api for tasks handling
api.route('/')
.post(function(req, res) {
var task = new Task({
creatorID: req.decoded.id,
creator: req.decoded.firstname + " " + req.decoded.lastname,
projectID: req.body.taskProjectID,
title: req.body.taskTitle,
description: req.body.taskDescription,
status: calcStatus(),
assigneeName: req.body.assigneeName,
assigneeID: req.body.assigneeID,
assignee_dept: req.body.assignee_dept,
estimate_cost: req.body.taskEstimate_cost,
actual_cost: req.body.TaskActual_cost,
last_modified_date: req.body.taskLast_modified_date,
due_date: req.body.taskDue_date,
start_date: req.body.taskStart_date,
complete_date: req.body.taskComplete_date,
});
task.save(function(err, newTask) {
if (err) {
res.send(err);
return;
}
io.emit('tasks', newTask);
res.json({
message: "New Task Created!"
});
});
})
.get(function(req, res) {
Task.find( {projectID: req.decoded.id}, function(err, task) {
if (err) {
res.send(err);
return;
}
res.json(task);
});
});
// api for angular
api.get('/me', function(req, res) {
res.json(req.decoded);
});
return api;
}
Thanks for the help.
You reference project.projects here:
<div class="panel-group" ng-repeat="eachProject in project.projects | reverse track by $index">
But project is never in ProjectController... I think you may want to set project to refer to your ProjectController, try this:
<div ng-controller="ProjectController as project">
EDIT
A few other problems. You mentioned you wanted to show all Tasks as well, in ProjectController you populate projects and tasks like so:
Project.all()
.success(function(data) {
vm.projects = data;
})
....
Task.all()
.success(function(data) {
vm.tasks = data;
})
That's good, except the definitions for Project.all and Task.all are referencing the same data source:
projectFactory.all = function() {
return $http.get('/api');
}
taskFactory.all = function() {
return $http.get('/api');
}
They both reference /api. How can they both expect different data from the same route? They should likely be two distinct routes.
In addition, your definition in api.js for this end point requires an ID to be passed to get a single project:
.get(function(req, res) {
Task.find( {projectID: req.decoded.id}, function(err, task) {
if (err) {
res.send(err);
return;
}
res.json(task);
});
});
.get(function(req, res) {
// The request must contain a creatorId, otherwise you're not going to find your project
Project.find( {creatorID: req.decoded.id}, function(err, project) {
if (err) {
res.send(err);
return;
}
res.json(project);
});
});
Perhaps your projectService should be pointing to the /all_projects end point instead for .all. So to sum up:
API end points for Project/Task should be different
Be sure to pass the project ID/task if necessary, otherwise you're not going to get the data you're expecting.
Set breakpoints and log output to trace your code path to see where other mistakes may be.

Resources