Having trouble updating $scope after integrating the Parse JS SDK into Angular.js services?

Apologies for any language barriers in my communication. I am currently working on developing a page for reporting current work progress. As part of this task, I have created a function called getWeek() to obtain the current week of the month and store user input in a Parse database. However, I am encountering an issue with updating the $scope variable while fetching data from the Parse JS SDK. Any assistance provided would be greatly appreciated. Please find the code snippet below.

angular.module('workReport', ["xeditable"])
    .run(function(editableOptions) {
        editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
    })
    .factory('Reports', function($q) {
        return {
            getData: function() {
                var defered = $q.defer();
                var data = getWeek();


                var query = new Parse.Query('workReport');

                query.find({
                    success: function(results) {
                        console.log("Successfully retrieved " + results.length + " scores.");

                        // Do something with the returned Parse.Object values
                        for (var i = 0; i < results.length; i++) {
                            var object = results[i];
                            for (var j = 0; j < data.length; j++) {
                                if (data[j].date.getTime() == object.get('date')) {
                                    data[j].activity = object.get('activity');
                                    data[j].mrngSession = object.get('mrngSession');
                                    data[j].afterSession = object.get('afterSession');
                                    data[j].completed = object.get('completed');
                                }
                            }
                        }

                        defered.resolve(data);
                    },
                    error: function(error) {
                        alert("Error: " + error.code + " " + error.message);
                    }
                });
                console.log(defered.promise)
                return defered.promise;
            }
        }
    })
    .controller('WeekReportCtrl', function($scope, Reports) {
        $scope.week = Reports.getData().then(function(r) {
          return r;
        }, function(r) { alert('Failed ' + r) })


    });

function getWeek() {
    var d = new Date
    d = d.toString().split(" ");
    var day = d[0];

    switch (day) {
        case 'Mon':
            return weeks(1, 1, 5);
            break;
        case 'Tue':
            return weeks(2, -1, 4);
            break;
        case 'Wed':
            return weeks(3, -2, 2);
            break;
        case 'Thu':
            return weeks(4, -3, 1);
            break;
        case 'Fri':
            return weeks(5, -4, 0);
            break;
        default:
            console.log('Nothing');
            break;
    }

    function weeks(d, s, e) {
        var week = [];
        for (var i = s; i <= e; i++) {
            var j = new Date;
            j.setHours(0, 0, 0, 0)
            var today = false
            if (i == 0) {
                today = true
            }
            j.setDate(j.getDate() + i);
            week.push({
                date: j,
                activity: "",
                mrngSession: "",
                afterSession: "",
                completed: 0,
                today: today
            });
        };
        return week;
    }
}

Answer №1

To achieve the desired result, it would be better to implement the following approach:

Reports.getData().then(function(response) {
      $scope.week = response;
}

Instead of assigning the promise object returned by Reports.getData() to $scope.week, make sure to assign the data passed to the success callback function of the then method.

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

AngularJS: Refresh array following the addition of a new item

After saving an object, I am looking to update an array by replacing the conventional push method with a custom function. However, my attempts have not been successful so far. Are there any suggestions on how to rectify this issue? app.controller("produ ...

Error encountered due to an unfinished string constant

We encountered a glitch in our software that triggers this error message. When navigating to a specific page in our ASP.NET 2.0 application, selecting "Yes" for debugging displays the page's source code. However, there is no JavaScript present on the ...

Using Express-session in the Internet Explorer browser

When configuring the express-session plugin, I follow this setup: var express = require('express'), session = require('express-session'), uuid = require('node-uuid'); var expiration_day = new Date('9/15/2015&apo ...

How to perfectly center a background image using CSS

I am currently working on a project that involves using a background image. However, I am facing some difficulties in trying to fully center the image, similar to what is shown in this My objective is https://i.sstatic.net/XUNTy.png What I have achieved s ...

The cookie appears in the callback URL, but does not get stored in the browser's cookie storage

I'm attempting to store the facebookPicUrl image in a cookie. Even though I can see it in the callback request, it's not showing up in the browser's cookie storage. Just to clarify, the session cookie is working fine. auth.route('/auth ...

Display information in a box when hovering using CSS and JQuery

I'm looking for an Info-Box (with the code <div class="inner">...</div>) that can determine if there is enough space available on the right, left, up, or down to display and adjust accordingly. While I've managed to check the space o ...

Trigger an event prior to the loading of a div

I have been working on a jQuery code that needs to run just before a specific div is displayed on the page. Take a look at the snippet below as an example of what I am trying to achieve: $(document).ready(function(){ $('.article').on('m ...

Creating real-time updates in Vuex and components using their data

There are two distinct elements here - a button and a form. By clicking the button, I can trigger an action in Vuex using "$store.dispatch". addWorkerSubmit: async function () { ... await this.$store.dispatch('workermanage/addWorkerSubmit ...

How should event listeners be unbound and child elements removed in single page applications?

I've recently delved into the world of memory leaks in JavaScript while working on a large single-page application. After using Chrome's Profiles (Snapshot) function, I noticed an abundance of detached DOM elements indicating a possible memory le ...

Ignore BBCode Within Code Blocks

I have searched through various resources on this particular issue, but none of them have provided the solution I am looking for. Currently, I am in the process of developing my own BBCode parser. However, I am facing a challenge regarding excluding the B ...

Error in Node-Fetch Mapping: Unable to access property 'map' of an undefined entity

Encountering an issue with the "map" section when attempting to run it - receiving an error message stating "Cannot read property 'map' of undefined" The customers constant is defined above, so I'm unsure where the undefined value is origin ...

webpack is failing to load SVG files

My application structure includes: /webapp /lib /assets ic_add_black_24px.svg ic_clear_black_24px.svg .. .. The configuration in my webpack.config.js looks like this: var path = require('path'), webpack = requ ...

Avoid TypeError: cannot read property '0' of undefined in a Vue.js/Django project

I am currently working on a Django/Vue.js application. Upon submitting the login form, the Django view redirects to the user's username page, where the Vue.Js file retrieves data from the server. Below is the code snippet: async created(){ await ...

Is there a simple method to sync with localStorage while preserving JavaScript data types?

My app is designed to interact with the localStorage by writing and reading data. Essentially, I have an array of objects that undergo frequent changes throughout the code, and I want these modifications to be synchronized with the data stored in the loca ...

Refreshing data attribute following an ajax request

I have this page with a list of various job listings. Each job listing has a button labeled "Paid" that includes a data-paid attribute indicating whether the job is paid or not. Whenever the "Paid" button is clicked, it sends a request to my route which u ...

Adding data to a multidimensional array in JavaScript

I am in need of creating a multidimensional JavaScript array dynamically, following this specific structure: array_answers[0][1]:"yes" array_answers[1][2]:"no" array_answers[2][2-subquestion]:"text input" array_answers[3][8]:"yes" array_answers[4] ...

Challenges when transitioning to TypeScript within a React project

I'm in the process of converting my React app Components to Typescript. After installing the TS package and setting up a tsconfig.json file and react-app-env.d.ts files, I made sure to change the file extensions from .js to .tsx. However, I encounter ...

What is the process for storing a file in a MongoDB database?

Currently, I am working on a small project where I need to store a document file in MongoDB database. I have been told that directly storing document files in MongoDB is not possible, but they can be stored in services like Google Drive or Dropbox and th ...

Tips for resolving CORS problems when trying to pull data from an API by utilizing jQuery AJAX and a JAVA backend

Currently, I am working on developing a front-end application to display data fetched from an API. This particular API was created using JAVA and Swagger.io by an android engineer. At the moment, the API does not have any authentication mechanism in place, ...

Automated Testing with Robot Framework: Utilizing Javascript to Click on a Button

Inspecting the web page <span jsslot=""> <button class="LkLjZd ScJHi IfEcue HPiPcc KXT7c" jsaction="click:yTqzwd" jsname="HxVe9c" autofocus="">Click Here</button> </span> I am tryin ...