Transferring information from a service to a controller in AngularJS version 1.3.15

I am facing a major issue in sending data from my StartingWebGazer service to WorkspaceController.js. The startingWebGazer service utilizes webgazer.js to evaluate prediction points, which are then passed to the xprediction and yprediction variables within StartingWebGazer.js.

app.service('startingWebGazer', function () {
this.startgazer = function () {
    window.onload = function () {
        webgazer.setRegression('ridge') /* must set regression and tracker */
            .setTracker('clmtrackr')
            .setGazeListener(function (data, elapsedTime) {
                if (data == null) {
                    return
                }
                var xprediction = data.x; //x coordinates relative to viewport
                console.log(xprediction);
                return xprediction;
            }).begin()
            .showPredictionPoints(true); 
        var setup = function () {
            var canvas = document.getElementById("plotting_canvas");
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            canvas.style.position = 'fixed';
        };

        function checkIfReady() {
            if (webgazer.isReady()) {
                setup();
            } else {
                setTimeout(checkIfReady, 100);
            }
        }

        setTimeout(checkIfReady, 100);

    };

    window.onbeforeunload = function () {
        console.log('user wants to leave the page');
        window.localStorage.clear(); 
    }
}});

I need to pass xprediction to WorkspaceController.js for future evaluations within the controller.

app.controller('WorkspaceController', ['$scope', 'startingWebGazer', function ($scope, startingWebGazer) {
$scope.startingWebGazer = startingWebGazer;
console.log($scope.startingWebGazer);
console.log('data in workspace', $scope.startingWebGazer.startgazer());}]);

However, I am encountering an issue where startgazer is undefined even though xprediction evaluates correctly (as shown by the console.log output). https://i.sstatic.net/Jj6gy.png

What could be causing this problem? Why can I see xprediction in the console.log but not pass it to the controller? What steps should I take to resolve this?

Answer №1

It appears that there may be some confusion regarding the functionality of startgazer. In its current definition, it does not return a value, as it only assigns actions to window.onload and window.onbeforeunload without a return statement, resulting in a return value of undefined. One possible solution could involve assigning the value of xprediction to a variable within the service scope and returning that variable. The following adjustment might address this issue:

app.service('startingWebGazer', function () {
    let x = 0;

    this.startgazer = function () {
        window.onload = function () {
            ...
            x = xprediction;
            ...
        }
        ...
    }

    this.getXPrediction = function() {
        return x;
    }
})

To improve the code further, it could be beneficial to consider calling startgazer within a run method or configuring getXPrediction to return a promise. Nevertheless, the provided example may serve as a starting point for resolving the issue at hand. I hope this information proves helpful.

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

Typescript HashMap implementation with Lists as values

Currently delving into TypeScript, I am attempting to generate a collection in a manner akin to the following Java example: HashMap<String, List<String>> hashMap = new HashMap<String,List<String>>(); Struggling to locate any releva ...

Is Vue function only operating after editing and refreshing?

I'm facing an unusual issue in my Vue function where it only seems to work after causing an error intentionally and then refreshing the page. The code itself works fine, but there's a problem with the initialization process. Can someone provide s ...

Utilizing module.exports and ES6 for exporting imports

I am currently facing an issue trying to import a function into a file and then export it from that file. It seems like a fairly straightforward task, but for some reason I am having trouble getting it to work. search_action.js function search_actions() ...

The ng-repeat directive is specifically designed to loop through a List object, and does not support iterating over Iterable

It appears that ng-repeat only works with Lists and not other types of iterables. For example, the following code does not produce the expected result: <span ng-repeat="i in [1, 2, 3].toSet()>{{i}}</span> An exception is thrown at package:an ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...

Completing the final touches on my jQuery typing enhancement feature

Currently, I have a code snippet that creates <li> elements with specific dimensions and background images when a user presses a key. The corresponding CSS class is applied to the generated <li>, displaying a specific character on the screen. H ...

Issue with Vuejs where changes are made to the parent array, but the child component does not detect those

I'm facing an issue where my parent component has the following code: {{ fencing }} <FencingTable v-if="fencing.length > 0" :fencing="fencing" :facility="facility" /> get fencing() { return this.$sto ...

Identify and sort JSON objects based on keys with multiple values

My JSON file contains objects structured like this: [ { "name" : "something", "brand": "x", "category" : "cars" }, { "name" : "something2 ...

How to best handle dispatching two async thunk actions in Redux Toolkit when using TypeScript?

A recent challenge arose when attempting to utilize two different versions of an API. The approach involved checking for a 404 error with version v2, and if found, falling back to version v1. The plan was to create separate async thunk actions for each ver ...

Ways to determine the total number of npm packages installed, excluding development dependencies

Is there a specific NPM command I can run from the CLI to count only the installed NPM Modules in my package that are not Dev Dependencies? When I use npm ls, it lists all packages without distinguishing between regular dependencies and DevDependencies. ...

Is it possible to dynamically set the pattern attribute of a form input to correspond with the value entered in another input within the same form?

The issue at hand is pretty straightforward - I have a form with the usual email setup: an Email input along with a Confirm Email input, where the values must match for validation. I'm curious if it's possible to dynamically set the pattern attr ...

What is the best way to display a series of interconnected tables in a specific order within MySQL using recursion?

Given: table dependencies listed in sequence (Generated by MySQL Forward Engineer script) tableA, NULL tableB, NULL tableB, tableA tableC, NULL tableC, tableA tableD, NULL tableD, tableC I am working with a MySQL database containing over 40 relational tab ...

Trouble Getting Results with getElementByClassName

I am facing an issue with my code. Originally, I was using getElementById(), but since the function needs to apply to multiple links, I switched to getElementByClassName(). However, it isn't returning any results. I have provided all the details on js ...

Issue with form validation, code malfunctioning

I am struggling to figure out why this validation isn't working. Here is the HTML code I'm using: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type='text/javascript' src="scripts. ...

"The JavaScript form appears to be malfunctioning as it is unable to calculate results based on

I'm currently working on a JavaScript form that aims to calculate the feeding volume based on various input factors such as feed type, number of feedings per day, target protein intake, current protein intake, and patient's weight. Although the ...

Display or conceal various content within div elements using multiple buttons

I have a set of 5 image buttons, each meant to trigger different content within a div. When the page loads, there should be default content displayed in the div that gets replaced by the content of the button clicked. The previously displayed content shoul ...

Capture all form inputs in a JavaScript array

I am struggling to collect all the form values into a regular array[]. Initially, I was able to achieve this for input tags but after adding some select tags, I am facing difficulties. Previously, for only input tags, this code worked: var content = docu ...

Updating the DOM does not occur by simply adding an object to the Array; instead, the database is updated once the data has

My database has verified data that is being updated, however, the DOM is not reflecting these updates. <ul> <li ng-repeat="aReview in reviewList"> .... .... </li> </ul> <script> if(globalMethods.stringVa ...

Troubleshooting issues with applying a class on load using JavaScript

I am new to Javascript and I am trying to add a class to an element when the page loads. Specifically, I want to change the background color of the element as a test. However, I keep running into the error message "Uncaught TypeError: Cannot read property ...

I am encountering an issue with a JS addition operator while working with node.js and fs library

I'm trying to modify my code so that when it adds 1 to certain numbers, the result is always double the original number. For example, adding 1 to 1 should give me 11, not 2. fs.readFile(`${dir}/warns/${mentioned.id}.txt`, 'utf8', ...