Creating a reusable function in AngularJS using the factory method

Currently, I am using the AngularJS factory method to retrieve data and passing that value to controllers.

  • In order to avoid creating separate functions, I would like to create a common function that can be utilized in all controllers.

  • How can I efficiently reuse code in a common function?

  • The different scopes such as scope.firstCard with 15 records, scope.secondCard with 6 records, scope.thirdCard with 130 records, and scope.fourthCard with 5 records each have varying values.

Please review the below factory code:

app.factory('commonService', ['$timeout', '$rootScope', '$state', '$window',
        function($timeout, $rootScope, $state, $window) {
        
var renderData1 = function(scope) {
                var convertedTime = scope.firstCard.forEach(function(card) {
                    if (card.Category == 'A') {
                        console.log("A");
                    } else if (card.Category == 'B') {
                        console.log("B");
                    } else if (card.Category == 'C') {
                        console.log("C");
                    } else if (card.Category == 'D') {
                        console.log("D");
                    } else if (card.Category == 'E') {
                        console.log("E");
                    }
                });
                return convertedTime;
            };
            var renderData2 = function(scope) {
                var convertedTime = scope.secondCard.forEach(function(card) {
                    if (card.Category == 'A') {
                        console.log("A");
                    } else if (card.Category == 'B') {
                        console.log("B");
                    } else if (card.Category == 'C') {
                        console.log("C");
                    } else if (card.Category == 'D') {
                        console.log("D");
                    } else if (card.Category == 'E') {
                        console.log("E");
                    }
                });
                return convertedTime;
            }

           
            var renderData3 = function(scope) {
                var convertedTime = scope.thirdCard.forEach(function(card) {
                    if (card.Category == 'A') {
                        console.log("A");
                    } else if (card.Category == 'B') {
                        console.log("B");
                    } else if (card.Category == 'C') {
                        console.log("C");
                    } else if (card.Category == 'D') {
                        console.log("D");
                    } else if (card.Category == 'E') {
                        console.log("E");
                    }
                });
                return convertedTime;
            }

            var renderData4 = function(scope) {
                var convertedTime = scope.fourthCard.forEach(function(card) {
                    if (card.Category == 'A') {
                        console.log("A");
                    } else if (card.Category == 'B') {
                        console.log("B");
                    } else if (card.Category == 'C') {
                        console.log("C");
                    } else if (card.Category == 'D') {
                        console.log("D");
                    } else if (card.Category == 'E') {
                        console.log("E");
                    }
                });
                return convertedTime;
            }

            return {
                renderData1: renderData1,
                renderData2: renderData2,
                renderData3: renderData3,
                renderData4: renderData4

            };
            }]);

Instead of this approach, I aim to create a single function and use it across multiple controllers. How can I achieve this?

                        if (card.Category == 'A') {
                            console.log("A");
                        } else if (card.Category == 'B') {
                            console.log("B");
                        } else if (card.Category == 'C') {
                            console.log("C");
                        } else if (card.Category == 'D') {
                            console.log("D");
                        } else if (card.Category == 'E') {
                            console.log("E");
                        }

Given that this condition is prevalent in most controllers, is there a way to consolidate and reuse it in one central location?

Answer №1

One way to streamline your code is by creating a shared service or factory, which can be accessed from all controllers in your application.

Here's an example:

app.factory('sharedService', ['$timeout', function($timeout){
    return {
        showData: function(data){
            console.log(data);
        },
        processData: function(data1, data2){

        }
    }
}])

app.controller('myController', ['$scope', 'sharedService', function($scope, sharedService){

    $scope.displayInfo = function(){
        sharedService.showData('Hello');
    }
}])

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 factors influence the speed of an Ajax request?

It is common knowledge that the amount of data transmitted to the server, as well as the volume of information returned in a call can greatly affect its speed. However, what I am curious about is whether the following factors might also impact the transmi ...

Encountered an issue while trying to register a service worker: "[ERROR] Cannot import statement outside

With the utilization of register-service-worker, the boilerplate for registerServiceWorker remained untouched. /* eslint-disable no-console */ import { register } from 'register-service-worker'; if (process.env.NODE_ENV === 'production&ap ...

Troubleshooting routing issues in MVC Web API and AngularJS

I am currently working with MVC Web API and Angular JS. Everything was running smoothly when I had a single routeProvider defined. However, as soon as I added another routeProvider, things started to break down... This is the code snippet causing me trou ...

Finding a problem in node.js

I have encountered a problem while creating a server game using node.js. I am seeking assistance to resolve this issue. Here is the specific problem: https://i.stack.imgur.com/FMlsL.png app.js: var express = require('express'); var app = expr ...

Executing the algorithm through a Node HTTP request results in a significant increase in processing time

My current Node app plots data on an x,y dot plot graph. To achieve this, I send a GET request from the front end to my back-end node server, which then processes the request by looping through an array of data points. Using Node Canvas, it draws a canvas ...

Merge Razor with Ajax and JSON

I have been struggling to get the following components to work together without success. The goal is to populate the mediaId's combobox with respective values based on the selection in the target combobox. Currently, I am only simulating the values fo ...

Tips for placing <div .right> above <div .left> when the window is small, given that <div .right> is positioned to the right of <div .left> when the window is large

I've come across a similar layout before, but I'm struggling to replicate it myself. The idea is to have text aligned on the left side with an image floated to the right. Instead of the image appearing below the text when the window size is red ...

A Node.js feature that enables atomic file replacement, triggering watchers only once

I have a unique scenario where I need to handle two types of processes. One process is responsible for writing a file, while the other processes are required to read it whenever there is a change. In my research, I came across fs.watch as a solution to ke ...

Unable to retrieve input field in protractor testing

Struggling with accessing an input field in AngularJS/Protractor for testing purposes. Despite the app setting the input fields to their initial values when running on the browser, I am unable to interact with them or modify their contents during testing. ...

Combining a variety of animations within a mesh

Can someone help me understand this specific example in Three.js? The link is . I am facing some difficulties with the BlendCharacter.js file. this.load = function ( url, onLoad ) { var scope = this; var loader = new THREE.JSONLoader(); load ...

Looking for the location of a matching brace in a dataset?

As a newbie in the world of coding, I have embarked on learning about NodeJs file system module. Currently, my focus is on handling a large data file stored as a string. The challenge that I am facing is with locating the matching close brace and its pos ...

An error was encountered involving an unexpected token < at the beginning of a JSON file while using express with firebase

After setting up an authentication system in express using firebase auth, I established an endpoint in my express server: app.post('/users/login', (req, res) => { console.log('logging in...'); firebase.auth().signInWithEmail ...

Automatically redirect to a different page upon clicking the jquery popup button

I integrated a jQuery popup feature on my website to display messages. Now, I am looking to implement a redirect to another page when the user clicks a button within the jQuery popup. However, I am unsure of how to achieve this. <script type="text/ja ...

Tips for creating a concise summary of written content

I am interested in creating an AI-powered summary generator for text input within a textarea element. Below is the HTML code snippet I have been working with: <textarea id="summary">Enter your text here</textarea> If you hav ...

Update the directive automatically whenever a change occurs in the root scope property

I am facing an issue with a directive that generates a random number. My goal is to reload or refresh this directive when a checkbox is toggled. Below is the code I have been using, but unfortunately, it's not working as expected. var app = angular. ...

Converting JSON POST data in Mocha test for an Express application

When I run my Express code from Postman, everything works perfectly. However, when I try to call it from Mocha, I encounter issues specifically with setting data in the header of a POST request. This problem only occurs with POST requests containing parame ...

Using Google Apps Script to retrieve post data from a web application through the `doPost` method

https://i.sstatic.net/2HpSJ.jpg When trying to access formIDArray in my appscript, it returns nothing. How can I properly access the object "FormIDArray[]" from the appscript environment? ...

Unable to stop React HTMLAudioElement from playing

In the realm of React, there exists a component that requires a URL input to function. The purpose of this component is to display a button that allows users to control the playback of an audio file. It's worth noting that this particular component is ...

Incorporate Subtitles into Your Website Using JWPlayer

I want to incorporate Video Captions similar to those seen on Lynda.com, for example at The captions should synchronize with the player and also appear in a separate block of HTML below the player. I am using JWPlayer for my video and have successfully in ...

Issue with Bootstrap Scrollspy: Scrollspy function not functioning as expected

I need help with creating a one-page website where the navbar links change based on the section of the page you are on. I tried implementing it using HTML, but it didn't work out as expected. The code I used was within the container holding different ...