Using AngularJS to access an array of scope variables and compute the average value

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!

Answer №1

In order to ensure accurate progress calculation, it is imperative to postpone the process (specifically lines 46 to 48 in project_controller.js) until all data has been successfully loaded. It is recommended to segregate the calculation into a fresh method and invoke this new method within the callback at line 6, as well as within another callback that needs to be generated at line 9.

Answer №2

It seems like you are attempting to access the project.tasks property before it has been initialized. I recommend wrapping this calculation within a function and invoking it in the success callback when fetching or updating projects.

$scope.updateProjects = function() {
    if (!$routeParams.id) {
      Project.query(function(data) {
        $scope.projects = data;
        $scope.calculateTasks();
      });
    } else {
        $scope.projects = Project.get({id: $routeParams.id})
    }
};

...
$scope.calculateTasks = function () {
    $scope.progs = [];
    for (var i = 0; i > $scope.projects.tasks.length; i++) {
        $scope.progs.push($scope.projects.tasks.array[i].progress);
    };
}
$scope.updateProjects();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What's the reason for the mousewheel functioning in Chrome but not in Firefox?

I am currently using CSS to enable scrolling up and down a popup page with just the mousewheel, but I'm facing an issue with it not working in FireFox. Surprisingly, it works fine in Chrome with the use of overflow-x:hidden; and overflow-y:auto; prope ...

Troubleshooting node modules for browser compatibility

Looking for assistance with running a specific node module in a browser. The module in question is called fury.js. I attempted to use browserify, however, encountered an error stating "ReferenceError: fury is not defined" when trying to utilize it. In th ...

What is the correlation between statistics and posts that are generated dynamically?

One interesting aspect to consider is how statistics are connected to individual posts. For instance, linking the like count to each Facebook post or tying upvote and downvote stats to a question on Stackoverflow presents some intriguing challenges. How ...

Creating a JavaScript function that generates a heading element

Hey there, I'm just starting out and could really use some guidance. I want to be able to have a function called addHeading() that takes the heading type selected from a drop-down menu and the text inputted in a form field, then creates and displays t ...

Encountering an issue following the installation and integration of an npm module within a Meteor

I recently started a project using the latest version of Meteor. I added a new package by running the command: meteor npm install --save name_of_package Since this package is meant for the client side, I created a file called mypackage.js inside the /cli ...

What are the best practices for effectively testing directives that involve DOM manipulation?

My inquiry begins with a preliminary question: Is it advisable to perform unit testing on DOM manipulation within Angular directives? Consider, for example, the following cohesive linking function: function linkFn(scope, element) { var ribbon = eleme ...

CSS compatibility across different browsers

Check out my jsFiddle for an example of an onHover event that changes the image. It's working perfectly in chrome, but not quite right in firefox. Any suggestions on how to fix it? Here's the jQuery function I'm using: $(document).ready(fu ...

Is it possible to utilize a factory nested within another factory to merge two separate REST requests?

Currently, I am working with two factories in my project: angular.module('categoryResource', ['ngResource', 'userResource']) .factory('categories', function ($http, users){ var factory = {}; factory.getCateg ...

Guide to running code repeatedly in node.js

Is there a way to repeat the console.log function 5 times in Node.js using the 'repeating' npm package? I am working on a node application that needs to run a specific code multiple times, but I can't seem to figure out how to achieve this. ...

Tips for implementing a countdown timer with JavaScript

I have created a program using HTML that functions like a website but works offline. I am looking to incorporate a 35-minute countdown timer that will automatically log out the user once the time is up. However, my current JavaScript code only counts down ...

Updating Angular 2 components using BaobabWould you like to learn how to

Exploring Baobab as a potential solution for developing Flux applications with Angular 2 has piqued my interest, but I have yet to come across any examples. My primary query revolves around the process of 'subscribing' an Angular Component to Ba ...

Do the items appear on screen only once you start typing in AngularJS?

Most things are working well except for a couple of issues Code var app = angular.module("MyApp", []); app.filter('offset', function() { return function(input, start) { start = parseInt(start, 10); return input.slice(start); }; } ...

Properly populating a 2D array

I'm struggling to come up with an algorithm to populate a square matrix as shown below: "The program prompts the user to enter a natural number, n, not exceeding 20. It then populates a square table according to the given criteria. The numbers be ...

transferring C pointers across numerous layers of function calls

Currently, I am working on a class assignment and would like to seek some assistance regarding the use of bubble sort. The task at hand involves sorting an array of random numbers using pointers. The initial setup of the array is as follows: int array[DA ...

Ensure that the fail callback function in jQuery ajax is triggered only after all retry attempts have failed

Utilizing ajax in conjunction with jQuery involves utilizing $.ajax which returns a promise known as ajaxPromise. The specific requirement is to have the ajaxPromise only catch failures if all retry attempts for the ajax calls have failed, with the goal of ...

Enhance the table using Django URL tag along with JQuery

I am currently working on a table that is being populated with user details and I would like to include a Django URL tag within the row, extracting the primary key in the process. Here is an example of what I am trying to achieve: function putTableData(re ...

Issue with mobile browser validation for text field functionality not functioning properly

Issue with text box validation on mobile browsers for my Angular application Mobile Browsers: Chrome, Samsung Browser (not working in both) Expected Input: Numbers 0-9 and Alphabets A-Z only in the text field My Approach : 1. Initial Attempt: I attempted ...

Techniques for linking <span> values to the radar chart's field titles using AngularJS or JQuery

Here is the code snippet containing a list of spans that are generated based on user input: <div id="tags" style="border:none"> <span class="tag" id="4"></span> <input type="text" id="inptags" value="" placeholder="Add max of 6 values ...

Whenever I click on <a href="whatever.aspx"></a>, I would like the page to be displayed within the current page

This is the code I am working with: <asp:DataList ID="dlGallery" runat="server" RepeatLayout="Flow" Width="100%" CellPadding="4" ForeColor="#333333"> <AlternatingItemStyle BackColor="White" ForeColor="#284775" /> <FooterStyle BackColor ...

Issue with loading Squarespace form when executing jQuery on Internet Explorer

One challenge I'm facing is that Squarespace builds their forms using JavaScript (YUI) and loads their code on document ready. How can I ensure that my code waits until their form is fully loaded? This issue seems to only occur in Internet Explorer. ...