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.
Related
Can anyone tell me, how Can i create urls in pagination. At this moment i have:
controller:
$scope.pagination = function(pages) {
return new Array(pages);
}
list:
<span ng-repeat="pagee in pagination(pages) track by $index" ng-if="$index < 10">
<button ng-if="page+$index < pages+1" ng-class="{ active: isActive(page+$index) }" ng-click='loadProducts(page+$index, pageSize)' class="btn btn-default">{{page+$index}}</button>
</span>
And question is how can I create url that, when I Click on button (4) is creating :
in url: numberPage and sizePage, and when I after enter this link, it will redirect me to this page.
I am working with node.js/angularJS
node:
router.get('/list', function(req, res, next) {
console.log(req.query);
res.render('product/list', {
title: 'Express'
});
});
router.get('/products', function(req, res) {
var size = parseInt(req.query.pageSize);
if (req.query.pageNumber == 1) {
var page = 0;
} else {
var page = parseInt(req.query.pageNumber) * req.query.pageSize - req.query.pageSize;
}
Product.count()
.exec(function(err, numberProducts) {
if (err) {
res.status(404).json({
message: 'Can not download this list'
})
} else {
Product.find().skip(page).limit(size)
.exec(function(err, products) {
if (err) {
res.status(404).json({
message: 'Can not download this list'
})
} else {
res.json({
"count": numberProducts,
"products": products
})
}
})
}
})
});
and url address when I'm in site with list products in first page:
http://localhost:3000/product/list
I'm using ngCordova File Transfer plugin in an ionic project to download set of images from urls. Here is the code i'm using for that.
// Save a image file in a given directory
$scope.saveImage = function(dir,imgUrl,imageName) {
var url = imgUrl;
var targetPath = cordova.file.dataDirectory+ dir+"/" + imageName;
var trustHosts = true;
var options = {};
// Download the image using cordovafiletransfer plugin
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
$scope.loadedCount ++;
$ionicLoading.show({template : "<ion-spinner class='spinner-energized'></ion-spinner><p> Downloading pages : "+ $scope.loadedCount+" of "+ $scope.pages.length+ "</p><p>Please wait...</p><p><button class=\"button button-block button-positive\">continue in background</button></p>"});
if($scope.loadedCount == $scope.pages.length) {
$ionicLoading.hide();
$scope.showDownloadSuccessAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Success!',
template: "Your magazine successfully downloaded. You can view it on Downloads!"
});
};
$scope.showDownloadSuccessAlert();
}
}, function(err) {
alert(JSON.stringify(err));
}, function (progress) {
if($scope.loadedCount > 80) {
}
});
};
// Download the current magazine
$scope.downloadMagazine = function() {
if($rootScope.user.user_id == undefined) {
$scope.showLoginAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Oops!',
template: "Your must login to download magazines"
});
};
$scope.showLoginAlert();
return;
}
document.addEventListener('deviceready', function () {
var dirName = $rootScope.currentIssue.slug+'_VOL_'+$rootScope.currentIssue.vol+'_ISU_'+$rootScope.currentIssue.issue;
// First create the directory
$cordovaFile.createDir(cordova.file.dataDirectory, dirName, false)
.then(function (success) {
var count = 1;
$scope.loadedCount = 0;
angular.forEach($scope.pages, function(value, key) {
var imgName = count+".png";
$scope.saveImage(dirName,value.link,imgName); // Then save images one by one to the created directory.
count++;
});
}, function (error) {
// Directory already exists means that the magazine is already downloaded.
$scope.showDownloadedAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Why worry!',
template: "Your have already downloaded this magazine. You can view it on downloads"
});
};
$scope.showDownloadedAlert();
});
}, false);
};
})
Problem here is that program try to download everything at once without waiting for previous one to finish. How to wait for one file to finish downloading and then start the other?
Thanks
If you want to do that automatically (you're not the first one : How can I execute array of promises in sequential order?), you could try reducing the list of address to a single Promise that will do the whole chain.
$scope.pages.reduce(function (curr,next) {
return curr.then(function(){
return $scope.saveImage(dirName, curr.link, imgName);
});
}, Promise.resolve()).then(function(result) {
$ionicLoading.show({template : "<ion-spinner class='spinner-energized'></ion-spinner><p> Downloading pages : "+ $scope.loadedCount+" of "+ $scope.pages.length+ "</p><p>Please wait...</p><p><button class=\"button button-block button-positive\">continue in background</button></p>"});
if($scope.loadedCount == $scope.pages.length) {
$ionicLoading.hide();
$scope.showDownloadSuccessAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Success!',
template: "Your magazine successfully downloaded. You can view it on Downloads!"
});
};
$scope.showDownloadSuccessAlert();
}
});
And don't forget to make your saveImage async which returns a promise.
UPDATE:
You will need to remove the then logic from your save method and return the download method call:
return $cordovaFileTransfer.download(url, targetPath, options, trustHosts).promise;
Then you can put your download handler into Promise.resolve()).then. See above.
There's no other way other than chaining your promises. Here's an example:
angular.module('app', [])
.service('fakeDownloadService', function($timeout) {
this.download = (file) => $timeout(() => file, 100);
return this;
})
.run(function($rootScope, $q, fakeDownloadService) {
var listOfFiles = [];
for (var i = 0; i < 10; i++)
listOfFiles.push('file' + i);
$rootScope.log = [];
$rootScope.download = () => {
listOfFiles
.reduce((prev, curr) => {
return prev.then((result) => {
if(result)
$rootScope.log.push(result + ' downloaded');
return fakeDownloadService.download(curr);
});
}, $q.resolve())
.then(() => $rootScope.log.push('all done'));
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<div ng-app="app">
<button ng-click="download()">Start</button>
<div>Log:</div>
<ul>
<li ng-repeat="entry in log track by $index">
{{entry}}
</li>
</ul>
</div>
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
I am making a small polls app with Yeoman's angular-fullstack generator. I have got to the stage where I am implementing user selection to increment a polls count, which then updates my MongoDB database via a PUT request.
Question is set up ready for the user to vote:
The object has individual IDs:
Then, a user goes to vote on an answer. Looks fine on the client:
But it's not updating correctly in the server. All items in the array change to the first item, with identical IDs:
When the client is refreshed, it loads the data from the server and obviously this is not what I want:
What am I doing wrong?
Here is the view:
<form ng-submit="submitForm()">
<div ng-repeat="answer in poll.answers">
<label><input type="radio" name="option" ng-model="radioData.index" value="{{$index}}"/>
{{ answer.value }} - {{ answer.votes }} Votes
</label>
</div>
<button class="btn btn-success" type="submit">Vote!</button>
</form>
Here is the controller:
'use strict';
angular.module('angFullstackCssApp')
.controller('ViewCtrl', function ($scope, $routeParams, $http) {
$http.get('/api/polls/' + $routeParams._id).success(function (poll) {
console.log(poll);
$scope.poll = poll;
$scope.radioData = {
index: 0
};
$scope.submitForm = function () {
console.log($scope.radioData.index);
$scope.poll.answers[$scope.radioData.index].votes += 1;
console.log('scope poll answers:- ', $scope.poll.answers);
console.log('scope poll answers[index]:- ', $scope.poll.answers[$scope.radioData.index]);
console.log('votes:- ', $scope.poll.answers[$scope.radioData.index].votes);
// Change database entry here
$http.put('/api/polls/' + $routeParams._id, {answers: $scope.poll.answers}).success(function () {
console.log('success');
});
};
});
});
Here is the relevant server-side code, all left from the default of my route and endpoint setting up:
router.put('/:id', controller.update);
// Updates an existing poll in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Poll.findById(req.params.id, function (err, poll) {
if (err) { return handleError(res, err); }
if(!poll) { return res.status(404).send('Not Found'); }
var updated = _.merge(poll, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.status(200).json(poll);
});
});
};
And the schema:
var PollSchema = new Schema({
creator: String,
title: String,
answers: [{
value: String,
votes: Number
}]
}, { versionKey: false });
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();
};