Tips for utilizing $scope in an AngularJS service

Currently, I am storing my API response in a $scope variable within my main controller. However, I realize that rewriting this code in each controller is slowing down my application. I am considering moving it to a service file and using it across all controllers.

MainController.js :

$scope.UserId = reply.split('UserId=').pop().toUpperCase();
apiService.getResponseData($scope.UserId).then(function(reply) {
  $scope.responseData = reply.data;
  $timeout(function() {
    reply.data.forEach(function(card) {
      if (card.Category == 'Apple') {
        console.log("Apple");
      } else if (card.Category == 'Google') {
        console.log("Google");
      } else if (card.Category == 'Microsoft') {
        console.log("Microsoft");
      } else if (card.Category == 'Amazon') {
        console.log("Amazon");
      }
    });
  });
});

This is my MainController. How can I refactor this code into a service file?

CommonService.js :

app.service('commonService', ['$timeout', '$rootScope', 'apiService',
  function($timeout, $rootScope, apiService) {
    this.app = function($scope) {
      $scope.UserId = reply.split('UserId=').pop().toUpperCase();
      apiService.getResponseData($scope.UserId).then(function(reply) {
        $scope.responseData = reply.data;
        $timeout(function() {
          reply.data.forEach(function(card) {
            if (card.Category == 'Apple') {
              console.log("Apple");
            } else if (card.Category == 'Google') {
              console.log("Google");
            } else if (card.Category == 'Microsoft') {
              console.log("Microsoft");
            } else if (card.Category == 'Amazon') {
              console.log("Amazon");
            }

          });
        });
      });
      return app;
    };
  }
]);

It's important to note that $scope won't work in the service file. Can someone assist me in modifying the code above so that it can be used from the service to multiple controllers?

Answer №1

Can be utilized, but not the most ideal scenario.

MainController.js :

commonService.performAction($scope);

CommonService.js:

app.service('commonService', ['$timeout', '$rootScope', 'apiService',
    function ($timeout, $rootScope, apiService) {
        var performAction = function (scope) {
            apiService.getData(scope.UserId).then(function (response) {
                scope.responseData = response.data;
                $timeout(function () {
                    response.data.forEach(function (item) {
                        if (item.Category == 'Apple') {
                            console.log("Apple");
                        } else if (item.Category == 'Google') {
                            console.log("Google");
                        } else if (item.Category == 'Microsoft') {
                            console.log("Microsoft");
                        } else if (item.Category == 'Amazon') {
                            console.log("Amazon");
                        }

                    });
                });
            });
        };

        return {
            'performAction': performAction
        }
    }
]);

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

Is there a way to verify if a checkbox has been checked?

Having trouble with this code: if($('#primayins').prop('checked')) { $("#tx_nm0x0_pricingplan").val(1); } else { $("#tx_nm0x0_pricingplan").val(2); } It keeps returning false consistently ...

Creating a new web application, I require a loading overlay to appear during transitions between pages

I've checked high and low, but I can't seem to find the solution! My webapp has a page that is bogged down with data causing it to load slowly. Is there a way to display a loading div while transitioning to the next page? Perhaps something like ...

Information derived from a provided URL

I am currently developing a Spotify stats app, and I am facing an issue with creating a context to store the token provided by the app in the URL when a user logs in. TokenContext.js: import React, { useEffect, useState } from "react"; // token ...

The redirect feature in Next.js 14 is experiencing delays

Having an issue with the redirect function in next.js 14. The problem is that the redirect process on the server takes approximately 5 minutes. I am currently using a VPS on Namecheap with WHM and cPanel, running the application on Apache server with passe ...

A malfunction report stemming from an HTTP error code while using react.js/javascript

In my react.js application, I have a Component that displays an error code. It currently looks like this: https://i.stack.imgur.com/2usiy.png Now, in addition to displaying just the code, I also want to show the reason for the error. Similar to how this ...

Protractor: What is the best way to retrieve the baseUrl from the command line input?

How can I retrieve the baseUrl that was passed through the command line in Protractor? For example: protractor conf.js --baseUrl=http://myawesomesite.com I attempted to use browser.baseUrl to access the baseUrl set in my conf.js file, but it does not see ...

I can't seem to locate the pageProps in nextjs v13. Can anyone

Previously in NextJS, there was a file called pages/_app.js that had the following default content: https://i.sstatic.net/nAvJf.png In this React component, we had a key called pageProps. However, when I upgraded to NextJS v13, I couldn't locate it. ...

What is the reason for not being able to utilize interpolation expression with "ng-model" while being able to do so with "ng-src"?

My current challenge involves attempting to utilize the interpolation expression alongside the ng-model directive, but unfortunately I haven't been able to get it functioning. Interestingly, when I apply interpolation with the ng-src directive, everyt ...

Creating uniform URLs using MVC .NET routing: a guide

While using ASP.Net MVC 5 in .NET Framework 4.8, I am constantly facing a 404 error due to inconsistent URL generation. For instance, when including the _PageNav.chstml partial at the top of each page and adding @Url.Action("Index", new { controller = "Hom ...

Encountering an error message stating "Please enable JavaScript to run this application" when making React API calls after deploying a ReactJs app on the Firebase server

I'm currently working on a React JS app that calls various APIs. The backend of this application is a NodeJs server deployed in GCloud. While everything runs smoothly when I test the React app locally, I encountered an issue after deploying it to Fir ...

Assistance needed for JavaScript link substitution

As I am wrapping up the web application version of my website, I have encountered a small issue. I need to convert the <script> var a=document.getElementsByTagName("a"); for(var i=0;i<a.length;i++) { a[i].onclick=functio ...

Fixing a div at the top post scroll - bug on iOS mobile device

I am looking to achieve a similar effect as demonstrated in the example below: https://css-tricks.com/scroll-fix-content/ Essentially, the goal is to have a div become fixed at the top of the page after scrolling to a certain point. Initially, the div wil ...

AngularJS ng-repeat to create a series of radio button options

This particular snippet of code generates two sets of radio buttons. The first set consists of individual radio buttons, while the second set is dynamically created using ng-repeat. Users can select any of the radio buttons by clicking on them directly or ...

Function that is triggered repeatedly when modifying the state within it

Within my render method, I am calling a handlePageClick function like this: onPageChange={this.handlePageClick} The function itself looks like this: handlePageClick = data => { this.setState({ circleloading: true }); let names = ...

Having trouble getting jQuery to function properly in Safari

I am facing an issue with jQuery in the Safari browser. While my jQuery functions are functioning perfectly on GC, FF, IE, and Opera, they seem to fail when tested on Safari. My question is: Is there a specific code snippet that I can integrate into my w ...

Is it an issue with my code or Regex101? Diagnosing JavaScript/Node error

I'm currently working on an exercise assigned by my school which involves using regex. However, I'm facing some confusion regarding whether the issue lies in my function or in my regex code. Our instructor advised us to use regex101.com for testi ...

Having trouble with the anchor tag not functioning properly

I'm looking to create a unique video experience by having an iframe video play automatically and opening a third-party video player in a lightbox style when clicked. Currently, the video autoplays, but I want it so that when the user clicks on the vi ...

Why are cloned jQuery elements triggering events on the parent <div> and not the child <div>?

Currently, I am working on a tool that includes dynamic input fields for user input. To create different sections, I have cloned some divs from the code successfully. However, I am facing an issue where the events attached to the parent div are triggered e ...

Transfer the content from a text area to a div element while keeping the original line breaks

I have a textarea and a div (containing a paragraph tag) where the content of the paragraph tag is updated with the text entered into the textarea upon keyUp. Is there a way to maintain line breaks from the textarea and have them appear as line breaks in ...

Finding the Number of Days Between Two Dates in AngularJS Using JavaScript

When I receive two dates from a web service in the format below: var dateone = "2016-08-21T07:00:00.000Z"; var datetwo = "2016-08-28T07:00:00.000Z"; var datediff = datetwo - dateone; var numdays = Math.round(datediff); console.log("Number of Days is " + n ...