Apologies if the question seems a bit disconnected from the title. Let me explain it here and provide a Gist with relevant code.
I have a JSON api that I access through AngularJS. It's a project with multiple tasks. I want to loop through the tasks in my $scope.projects variable (in my projects controller), extract all the 'progress' values for each task, calculate the average of these values to determine the overall progress of the project, and then assign it to a $scope variable for use in my template.
I'm having trouble accessing the tasks array, despite trying various methods, and I'm not sure why. So, I thought seeking advice here might be a good idea. Any assistance would be greatly appreciated.
Gist: https://gist.github.com/Tasemu/8002741
JS
App.controller('ProjectCtrl', ['$scope', 'Project', 'Task', '$routeParams', '$location', function($scope, Project, Task, $routeParams, $location) {
$scope.updateProjects = function() {
if (!$routeParams.id) {
Project.query(function(data) {
$scope.projects = data;
});
} else {
$scope.projects = Project.get({id: $routeParams.id})
}
};
$scope.deleteProject = function(project) {
Project.delete({id: project.id}, function() {
$scope.updateProjects({id: project.id});
$location.path('/');
});
};
$scope.deleteTask = function(task) {
Task.delete({id: task.id}, function() {
$scope.updateProjects({id: task.id});
});
};
$scope.updateProject = function(formData) {
$scope.projects.name = formData.name;
$scope.projects.description = formData.description;
$scope.projects.client = formData.client;
$scope.projects.due = formData.due;
$scope.projects.$update({id: formData.id}, function() {
$location.path('/');
});
};
$scope.saveProject = function(project) {
Project.save({}, project, function() {
$location.path('/');
});
};
$scope.updateProjects();
$scope.progs = [];
for (var i = 0; i > $scope.projects.tasks.length; i++) {
progs.push($scope.projects.tasks.array[i].progress);
};
}]);
JSON
{
id: 1,
name: "Project 1",
description: "this project",
client: "monty",
due: "2013-12-15",
tasks: [
{
id: 2,
name: "Task 2",
progress: 22,
project_id: 1,
created_at: "2013-12-17T03:08:53.849Z",
updated_at: "2013-12-17T05:06:31.602Z"
},
{
id: 1,
name: "Task 1",
progress: 75,
project_id: 1,
created_at: "2013-12-17T03:08:53.845Z",
updated_at: "2013-12-17T05:25:50.405Z"
}
],
created_at: "2013-12-17T03:08:53.719Z",
updated_at: "2013-12-17T06:57:52.699Z"
}
JS
App.factory('Project', function($resource) {
return $resource(
'/api/v1/projects/:id.json',
{id: '@id'},
{
update: {
method: 'PUT',
params: { id: '@id' },
isArray: false
}
}
);
});
If you require additional information, feel free to ask!