angular.js - updating sortorder in model from view - angularjs

I have an Express Model/Controller, getting data from a mongoDB collection. One of the columns in this collection is sortOrder (which I use to display the entries in a specific order). To manage the data from this collection, I have an angular.js view with a table, listing these entries.
This table is constructed using ui-sortable, which allows me to drag-a-drop table rows, i.e. changing the display order. Up to this point everything works as expected.
Now, my question is: how do I get my model/controller to recognise these changes, and update the sortOrder column in the collection, to now show the new sorting order?
Here's the code of the view:
<section data-ng-controller="BusinessunitsController" data-ng-init="find()">
<div class="page-header">business units</div>
<table>
<thead>
<tr>
<th><i class="icon-fontawesome-webfont-141"></i></th>
<th>business unit name</th>
<th><i class="icon-fontawesome-webfont-241 right"></i></th>
</tr>
</thead>
<tbody ui-sortable ng-model="businessunits">
<tr data-ng-repeat="businessunit in businessunits">
<td class="draggable">{{businessunit.sortOrder}}</td>
<td style="color:{{businessunit.color}}">{{businessunit.name}}</td>
<td>
<a data-ng-href="#!/businessunits/{{businessunit._id}}"><i class="icon-fontawesome-webfont-65"></i></a>
<a data-ng-href="#!/businessunits/{{businessunit._id}}"><i class="icon-fontawesome-webfont-240 alert"></i></a>
</td>
</tr>
</tbody>
</table>
</section>
Angular controller:
'use strict';
// Businessunits controller
angular.module('businessunits').controller('BusinessunitsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Businessunits',
function($scope, $stateParams, $location, Authentication, Businessunits) {
$scope.authentication = Authentication;
// Create new Businessunit
$scope.create = function() {
// Create new Businessunit object
var businessunit = new Businessunits({
name: this.name,
color: this.color,
sortOrder: this.sortOrder
});
// Redirect after save
businessunit.$save(function(response) {
$location.path('businessunits/' + response._id);
});
// Clear form fields
this.name = '';
};
// Remove existing Businessunit
$scope.remove = function(businessunit) {
if (businessunit) {
businessunit.$remove();
for (var i in $scope.businessunits) {
if ($scope.businessunits[i] === businessunit) {
$scope.businessunits.splice(i, 1);
}
}
} else {
$scope.businessunit.$remove(function() {
$location.path('businessunits');
});
}
};
// Update existing Businessunit
$scope.update = function() {
var businessunit = $scope.businessunit;
businessunit.$update(function() {
$location.path('businessunits/' + businessunit._id);
});
};
// Find a list of Businessunits
$scope.find = function() {
Businessunits.query(function(businessunits) {
$scope.businessunits = businessunits;
});
};
// Find existing Businessunit
$scope.findOne = function() {
Businessunits.get({
businessunitId: $stateParams.businessunitId
}, function(businessunit) {
$scope.businessunit = businessunit;
});
};
}
]);
Express controller:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Businessunit = mongoose.model('Businessunit'),
_ = require('lodash');
/**
* Create a Businessunit
*/
exports.create = function(req, res) {
var businessunit = new Businessunit(req.body);
businessunit.user = req.user;
businessunit.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
businessunit: businessunit
});
} else {
res.jsonp(businessunit);
}
});
};
/**
* Show the current Businessunit
*/
exports.read = function(req, res) {
res.jsonp(req.businessunit);
};
/**
* Update a Businessunit
*/
exports.update = function(req, res) {
var businessunit = req.businessunit;
businessunit = _.extend(businessunit, req.body);
businessunit.save(function(err) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(businessunit);
}
});
};
/**
* Delete an Businessunit
*/
exports.delete = function(req, res) {
var businessunit = req.businessunit;
businessunit.remove(function(err) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(businessunit);
}
});
};
/**
* List of Businessunits
*/
exports.list = function(req, res) {
Businessunit.find().sort('sortOrder').populate('user', 'name').exec(function(err, businessunits) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(businessunits);
}
});
};
/**
* Businessunit middleware
*/
exports.businessunitByID = function(req, res, next, id) {
Businessunit.findById(id).populate('user', 'name').exec(function(err, businessunit) {
if (err) return next(err);
if (!businessunit) return next(new Error('Failed to load Businessunit ' + id));
req.businessunit = businessunit;
next();
});
};
/**
* Businessunit authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.businessunit.user.id !== req.user.id) {
return res.send(403, 'User is not authorized');
}
next();
};

Related

TypeError: v2.UpdataData is not a function

I am new to Angular and MVC , and I have created a code for display
records into table view.
User can edit and delete that records by clicking the Edit and Delete
Link
but it shows me error when i click on edit link TypeError:
v2.UpdataData is not a function
and it also shows me error TypeError: $http.get is not a function
when i click on Delete Link
Can anyone help me to solve this out. Thanks in advance.
Controller.js
//update data of table
$scope.UpdataData = [];
//UpdateData();
$scope.UpdateData = function (StateMaster) {
var RetValData = DataService.UpdateStudent(StateMaster);
debugger;
getData.then(function (StateMaster) {
debugger;
StateID: $scope.StateID;
StateName: $scope.StateName;
CountryName: $scope.CountryName;
}, function () {
alert('Error in getting records');
});
}
$scope.DeleteData = [];
$scope.DeleteData = function (r, index) {
var retval = DataService.DeleteData(r.StateID).success(function (msg) {
$scope.countrydata.splice(index, 1);
alert('Student has been deleted successfully.');
}).error(function () {
alert('Oops! something went wrong.');
});
}.factory('DataService', function ($http) {
var fac={}
debugger;
fac.UpdateData= function($http)
{
return $http.get('/State/UpdateData');
}
return fac;
}).factory('DataService', function () {
var fac={}
debugger;
fac.DeleteData = function ($http)
{
return $http.get('/State/DeleteData');
}
return fac;
});
StateController.cs
public string UpdateData(StateMaster r)
{
if (r != null)
{
using (simpleEntities dbContext = new simpleEntities())
{
StateMaster lstdata = dbContext.StateMasters.Where(x => x.StateID == r.StateID).FirstOrDefault();
lstdata.StateName = r.StateName;
lstdata.CountryName = r.CountryName;
dbContext.SaveChanges();
return "Data Updated";
}
}
else
{
return "something went worng";
}
}
[HttpPost]
public string DeleteData(int id)
{
if (id != 0)
{
using (simpleEntities databContext = new simpleEntities())
{
var lsdata = databContext.StateMasters.Where(x => x.StateID == id).FirstOrDefault();
databContext.StateMasters.Remove(lsdata);
databContext.SaveChanges();
return "Data Deleted Successfully";
}
}
else {
return "Error Occured";
}
}
InsertState.cshtml
<div ng-app="MyApp" ng-controller="StateController">
<table class="table table-bordered">
<tr>
<td>Sr. No.</td>
<td>Country Name</td>
<td>State Name</td>
<td></td>
#*<td>Country Name</td>*#
</tr>
<tr ng-repeat="r in countrydata">
<td>{{$index + 1}}</td>
<td>{{r.CountryName}}</td>
<td>{{r.StateName}}</td>
#*<td>{{r.CountryName}}</td>*#
<td>
<span ng-click="UpdataData(r)" class="btnAdd">Edit</span> |
<span ng-click="DeleteData(r)" class="btnRed">Delete</span>
</td>
</tr>
</table>
</div>
there is problem in you code with this
line $scope.UpdateData = function (StateMaster
as you are trying to run fuction of your $scop but fuction is of factory so you have to try like
factory.UpdateDate
Seem like there is problem in defining factory in angular , you can try below way
var app = angular.module('myApp', []);
app.factory('testFactory', function(){
return {
sayHello: function(text){
return "Factory says \"Hello " + text + "\"";
},
sayGoodbye: function(text){
return "Factory says \"Goodbye " + text + "\"";
}
}
});
function HelloCtrl($scope, testService, testFactory)
{
$scope.fromFactory = testFactory.sayHello("World");
}
you can place your function and just try out it return you value or not

Meanstack /Angular.js how to update a seperate model

I'm writing a management system for an ecommerce system. The app needs to create pricing rules on a per product/ per category basis.
SO ..... For a new price rule that has a CategoryID, I want to update all products with that CategoryId. How do I call all the Products from the pricing controller and then update them?
I want this function in the Pricing's controller to update Products with a CategoryId that was set in the form.
$scope.saveRule = function saveRule(row){
var CategoryId = row.CategoryId;
if(row.id =="newRecord"){
var roundup = $('#roundupnewRecord').val();
var percentage = $('#percentagenewRecord').val();
var pricing = new Pricing({
CategoryId: CategoryId,
roundup: roundup,
percentage: percentage
});
pricing.$save(function(response) {
$route.reload();
});
} else {
Pricing.get({
pricingId: row.id
}, function(pricing) {
pricing.roundup = $('#roundup'+row.id).val();
pricing.percentage = $('#percentage'+row.id).val();
pricing.$update(function() {
$route.reload();
});
});
}
}
Thanks in advance for any help.
Pricing Controller. - angular
'use strict';
angular.module('mean.pricing').controller('PricingController', [ '$route', '$http', '$scope', '$routeParams', '$location', 'Global', 'Pricing', function ($route, $http, $scope, $routeParams, $location, Global, Pricing) {
$scope.global = Global;
$scope.create = function() {
var pricing = new Pricing({
CategoryId: this.title,
content: this.content
});
pricing.$save(function(response) {
console.log(response);
$location.path('pricing/' + response.id);
});
this.title = '';
this.content = '';
};
function generateDefaultRule() {
return {
CategoryId: 0,
ProductId: '',
roundup: 2,
percentage: 1,
newRecord: 1,
id: 'newRecord'
}
}
$scope.addRule = function addRule(id) {
$scope.rowCollection.push(generateDefaultRule());
console.log();
};
$scope.saveRule = function saveRule(row){
var CategoryId = row.CategoryId;
if(row.id =="newRecord"){
var roundup = $('#roundupnewRecord').val();
var percentage = $('#percentagenewRecord').val();
var pricing = new Pricing({
CategoryId: CategoryId,
roundup: roundup,
percentage: percentage
});
pricing.$save(function(response) {
$route.reload();
});
} else {
Pricing.get({
pricingId: row.id
}, function(pricing) {
pricing.roundup = $('#roundup'+row.id).val();
pricing.percentage = $('#percentage'+row.id).val();
pricing.$update(function() {
$route.reload();
});
});
}
//Get Products with Relative CategoryId
}
$scope.update = function() {
var pricing = $scope.pricing;
if (!pricing.updated) {
pricing.updated = [];
}
pricing.updated.push(new Date().getTime());
pricing.$update(function() {
$location.path('pricing/' + pricing.id);
});
};
$scope.find = function() {
Pricing.query(function(pricing) {
$scope.pricing = pricing;
});
};
$scope.findOverall = function() {
$http.get('/Pricing/overall').then(function(pricing) {
$scope.overall = pricing;
});
};
$scope.findCategories = function() {
$http.get('/Pricing/categories').then(function(pricing) {
console.log(pricing);
$scope.categories = pricing.data;
});
};
$scope.findProducts = function() {
$http.get('/Pricing/products').then(function(pricing) {
$scope.products = pricing.data;
});
};
$scope.findOne = function() {
Pricing.get({
pricingId: $routeParams.pricingId
}, function(pricing) {
$scope.pricing = pricing;
});
};
$scope.remove = function(pricing) {
if (pricing) {
pricing.$remove();
for (var i in $scope.pricing) {
if ($scope.pricing[i] === pricing) {
$scope.pricing.splice(i, 1);
}
}
}
else {
$scope.pricing.$remove();
$location.path('pricing');
}
};
$scope.removeItem = function removeItem(row) {
Pricing.get({
pricingId: row.id
}, function(pricing) {
pricing.$remove(function() {
var index = $scope.rowCollection.indexOf(row);
if (index !== -1) {
$scope.rowCollection.splice(index, 1);
}
});
});
}
$scope.list = function(){
$('table').on('click', 'a' , function (event) {
var id = $(this).attr('id');
if($(this).hasClass('editButton')){
$('#percentage'+id).css('display','inline-block');
$('#roundup'+id).css('display','inline-block');
$('#percentageSpan'+id).css('display','none');
$('#roundupSpan'+id).css('display','none');
$('.actionButtonsDiv'+id).css('display','none');
$('#saveButtonDiv'+id).css('display','inline');
}
});
$http.get('/pricing').then(function(pricing) {
$scope.rowCollection = pricing.data;
});
$http.get('/category').then(function(categories) {
$scope.categories = categories.data;
});
}
}]);
Products Controller - angular
'use strict';
angular.module('mean.products').controller('ProductsController', ['$http', '$scope', '$routeParams', '$location', 'Global', 'Products', function ($http, $scope, $routeParams, $location, Global, Products) {
$scope.global = Global;
$scope.create = function() {
var product = new Products({
title: this.title,
content: this.content
});
product.$save(function(response) {
$location.path("products/" + response.id);
});
this.title = "";
this.content = "";
};
$scope.remove = function(product) {
if (product) {
product.$remove();
for (var i in $scope.products) {
if ($scope.products[i] === product) {
$scope.products.splice(i, 1);
}
}
}
else {
$scope.product.$remove();
$location.path('products');
}
};
$scope.update = function() {
var product = $scope.product;
if (!product.updated) {
product.updated = [];
}
product.updated.push(new Date().getTime());
product.$update(function() {
$location.path('products/' + product.id);
});
};
$scope.find = function() {
Products.query(function(products) {
// console.log(products);
$scope.products = products;
});
};
$scope.categories = function() {
var selected = {};
$('#multiple').on('click', function(){
$('.product-checkbox').each(function() {
if ($(this).is(":checked")) {
$(this).prop('checked', false);
}else{
$(this).prop('checked', true);
}
});
});
$.each( ['approveButton', 'rejectButton', 'multiButton'], function( index, value ){
$('.'+value).on('click', function(){
$('.product-checkbox').each(function() {
var productId = $(this).attr('id');
if ($(this).is(":checked")) {
if (value === 'rejectButton') {
var categoryId = 199;
}else{
var categoryId = $('#selectProduct'+$(this).attr('id')).val().replace('number:','');
}
Products.get({
productId: productId
}, function(product){
product.CategoryId = categoryId;
product.$update(function(result) {
});
});
}
//Approves checked and rejcts unchecked products
if (value == 'multiButton') {
if (!$(this).is(":checked")) {
Products.get({
productId: productId
}, function(product){
product.CategoryId = 199;
product.$update(function() {
});
});
}
}
});
$location.path('products/categories');
});
});
$http.get('/products/categories').then(function(products) {
$scope.products = products.data;
});
$http.get('/category').then(function(categories) {
$scope.categories = categories.data;
});
$http.get('/productCategoryMatchs').then(function(productCategoryMatchs) {
var pCMResponse = productCategoryMatchs.data;
var pcmArray = {};
for(var index in pCMResponse){
pcmArray[pCMResponse[index].ProductId] = pCMResponse[index].CategoryId;
}
$scope.pCMs = pcmArray;
});
};
$scope.findOne = function() {
Products.get({
productId: $routeParams.productId
}, function(product) {
$scope.product = product;
});
};
}]);
Products Controller -node
'use strict';
/**
* Module dependencies.
*/
var StandardError = require('standard-error');
var db = require('../../config/sequelize');
/**
* Find product by id
* Note: This is called every time that the parameter :productId is used in a URL.
* Its purpose is to preload the product on the req object then call the next function.
*/
exports.product = function(req, res, next, id) {
console.log('id => ' + id);
db.Product.find({ where: {id: id}}).then(function(product){
if(!product) {
return next(new Error('Failed to load product ' + id));
} else {
req.product = product;
return next();
}
}).catch(function(err){
return next(err);
});
};
/**
* Create a product
*/
exports.create = function(req, res) {
// augment the product by adding the UserId
req.body.UserId = req.user.id;
// save and return and instance of product on the res object.
db.Product.create(req.body).then(function(product){
if(!product){
return res.send('users/signup', {errors: new StandardError('Product could not be created')});
} else {
return res.jsonp(product);
}
}).catch(function(err){
return res.send('users/signup', {
errors: err,
status: 500
});
});
};
/**
* Update a product
*/
exports.update = function(req, res) {
// create a new variable to hold the product that was placed on the req object.
var product = req.product;
product.updateAttributes({
price: req.body.price,
CategoryId: req.body.CategoryId
}).then(function(a){
return res.jsonp(a);
}).catch(function(err){
return res.render('error', {
error: err,
status: 500
});
});
};
/**
* Delete an product
*/
exports.destroy = function(req, res) {
// create a new variable to hold the product that was placed on the req object.
var product = req.product;
product.destroy().then(function(){
return res.jsonp(product);
}).catch(function(err){
return res.render('error', {
error: err,
status: 500
});
});
};
/**
* Show an product
*/
exports.show = function(req, res) {
// Sending down the product that was just preloaded by the products.product function
// and saves product on the req object.
return res.jsonp(req.product);
};
/**
* List of Products
*/
exports.all = function(req, res) {
db.Product.findAll({}).then(function(products){
return res.jsonp(products);
}).catch(function(err){
return res.render('error', {
error: err,
status: 500
});
});
};
/**
* List of Products
*/
exports.list = function(req, res) {
db.Product.findAll({
limit : 20
}).then(function(products){
return res.jsonp(products);
}).catch(function(err){
return res.render('500', {
error: err,
status: 500
});
});
};
/**
* List of Products and there categories
*/
exports.categories = function(req, res) {
db.Product.findAll({
attributes : [
'name',
'id',
// 'ProductCategoryMatch.count'
],
where: {
CategoryId : null
},
// include : [
// { model: db.ProductCategoryMatch }
// ],
// order : [
// ]
limit: 20
}).then(function(products){
return res.jsonp(products);
}).catch(function(err){
return res.render(500, {
error: err,
status: 500
});
});
};
/**
* Article authorizations routing middleware
*/
exports.hasAuthorization = function(req, res, next) {
// if (req.product.User.id !== req.user.id) {
// return res.send(401, 'User is not authorized');
// }
next();
};

Thinkster MEAN stack tutorial, deletion of element

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

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.

error performing a get request

I am trying to perform a get request, in the post request everything is OK, I can see that in the post request all I do it's been save, once I refresh the page I am printing in the console the items saved by the post request, but those items aren't been return with the get I am doing.
here is where everything begins, I have a list of items here with the option to checked or unchecked the items in the list
<ion-item ng-repeat="sport in sports" ng-click="toggleSportSelection(sport)">
{{:: sport.name}}
</ion-item>
all the items are checked = true by default, so what I am saving, are the items with checked = false, the items checked = true you can see them here
<div ng-show="sport.checked" ng-repeat="sport in sports">
{{sport.name}}
</div>
this is what I have in the controller
.controller('SportsController', function($scope, SportsFactory) {
SportsFactory.getSportChecked(customer).then(function(sportChecked) {
_.each(sports, function(sport) {
var sportIds = _.pluck(sport, 'id'),
intersectedSports = _.intersection(sport.id, sportChecked),
checkedSportObjects = _.filter(sport, function(sportObj) {
return _.includes(intersectedSports, sportObj);
});
_.each(checkedSportObjects, function(sport) {
$scope.sports.push(sport);
});
});
}, function(err) {
console.log(err);
});
$scope.toggleSportSelection = function(sport) {
var params = {};
params.user = $scope.customer.customer;
params.sport = sport.id;
sport.checked = !sport.checked;
SportsFactory.setSportChecked(params);
};
// this is what puts the sports on checked = true
if (sports.length) {
$scope.sports = _.map(sports, function(sport) {
sport.checked = true;
return sport;
});
}
and this is the service / factory
.factory('SportsFactory', function($http, $q, AuthFactory,
LocalForageFactory, CONSTANT_VARS) {
return {
getSportChecked: function(customer) {
var defer = $q.defer(),
user,
rejection = function(err) {
console.log(err);
defer.reject(err);
};
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED)
.then(function(sportChecked) {
user = customer.customer;
if (!_.isNull(sportChecked)) {
defer.resolve(sportChecked);
}else {
$http.get(CONSTANT_VARS.BACKEND_URL + '/sports/getChecked/' + user)
.success(function(sportChecked) {
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED, sportChecked);
defer.resolve(sportChecked);
})
.error(rejection);
}
}, rejection);
return defer.promise;
}
});
I am working along with NodeJS, so if you want the code I have in that part just let me know, so far I think that the issue I have is in the front end part, in the controller.

Resources