a single function spread across two controllers[JavaScript]

My query pertains to a JavaScript program with 2 controllers. The issue I am facing is the need for one function in both controllers (data.duration). This function serves two purposes, once for features themselves and once for the summary. Currently, this function is duplicated in the code...

Is there a way to utilize the function in both controllers efficiently?

(function() {

    var loader = ['$http',
        function($http) {
            return $http.get('report.json')
                .success(function(data) {

                    // Function declarations and logic here...

                    data.duration = function(feature) {
                        // Calculation logic goes here...
                    };

                });
        }
    ];

    // Angular module definitions, configuration, and controller functions...

}());

Answer №1

To simplify things, create a service and inject it into both controllers for easy access.

app.service("utilityService", function () {
    return {
        duration: function (feature) {
            ...insert your code here
        }
    }
});

Next, inject the utility service into each controller:

app.controller('FeatureListCtrl', function($rootScope, $scope, $location, $filter, report, utilityService) {

});

Now you can reference the utility service in your controllers like this:

utilityService.duration($scope.whatEverData)

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

Unable to parse JSON elements using jQuery

Currently, I have an unordered list containing customer names that are retrieved from a JSON file. I am trying to implement a click event using jQuery, but it seems to be having trouble reading it. While the list appears correctly in the HTML source file, ...

Coat the div with a uniform shade of pure white

I need assistance on applying a solid white background color to hide the text behind it. For better understanding, I have attached a screenshot as a reference. https://i.stack.imgur.com/f8Qd9.png The issue arises when I click on the dropdown in the heade ...

A method for performing precise division on numbers in JavaScript, allowing for a specific precision level (such as 28 decimal places)

I've searched extensively for a library that can handle division operations with more than 19 decimal places, but to no avail. Despite trying popular libraries like exact-math, decimal.js, and bignumber.js, I have not found a solution. How would you ...

What causes images to expand automatically when selected in my JavaScript gallery?

I am struggling with a simple JS gallery of images where I want to display a large image at the top and small thumbnails below it. The issue I am facing is that when I hover over an image in the thumbnail section, the big image changes as expected. However ...

Is it possible to dynamically override inline styles?

My HTML code is as follows: <div title="remove css"style="position:relative;">Remove my style</div> After the page loads, I need to completely remove the position style attribute. Due to limitations, I cannot override the CSS. Is there a way ...

Error: Node application using Express does not display 'Server Started' message in console upon execution

I'm encountering an issue where I don't see the "Server Start: 3001" message on the console when I run 'node app.js' in the terminal. Below is the content of my app.js file: var createError = require('http-errors'); var exp ...

The functionality of "Body Onload" for sending "ScrollHeight" is malfunctioning in Chrome and Safari

I came across an issue where the iframe_resize function in my code was not working as expected. After investigating further, I realized that the problem did not lie with the function itself. So, I decided to post a new question. Within my index.html file ...

Refreshing the page causes JavaScript to fail loading

Recently, I encountered a puzzling error. Upon visiting this link The carousel fails to load properly near the bottom of the page. However, if you click on the logo or navigate back to the home page, it works fine. Additionally, performing a command + r ...

Next.js endeavors to interpret MDX files as basic JavaScript code

Currently, I'm in the process of creating a website using Next.js and incorporating (local) MDX files for my content. However, I've encountered an issue where whenever I add a .MDX file to my source tree and attempt to navigate to it, Next.js thr ...

The jQuery code functions smoothly on computers, but experiences delays when running on an iPhone

I was working on my website and trying to add a div that sticks to the top of the browser when it scrolls out of view. I found a script that works well on desktop, but when testing it on iPhone, there is a slight delay before the div pops back up in the ri ...

What specific portion of the code will be transformed into a virtual DOM?

As a newcomer to the virtual DOM concept, I have been pondering how it functions over the past few days. Let's envision that I have integrated a simple template engine like twig into my project, and I am utilizing vue.js as my chosen javascript frame ...

Hybrid application: Manipulate HTTP user agent header using AngularJS

I am currently developing a hybrid app using Cordova and Ionic. My current challenge involves making an HTTP request to access a server where I need to modify the user agent of the device in order to pass a secret key. $http({ method: 'GET&a ...

Could one potentially use jQuery to navigate through JSON output?

My goal is to generate a JSON list that includes CSS classes and their respective URL records. Here's an example: var jsonList = [{ "CSSClass": "testclass1", "VideoUrl": "/Movies/movie.flv" }, { "CSSClass": "testclass2", "VideoUrl": "/Movies/ ...

How can I attach a click event to the left border of a div using jQuery?

I am wondering about a div element <div id="preview"> </div> Can anyone suggest a method to attach a click event specifically to the left border of this div? Your help is greatly appreciated. ...

Why does the UseEffect hook in next.js result in 2 fetch requests instead of the expected 1?

I am encountering an issue where my code is triggering two requests to my API using the GET endpoint. Unfortunately, my understanding of useEffect() is not deep enough to pinpoint where the problem lies. I want to avoid putting unnecessary strain on the ...

Uncover the secrets of extracting query parameters from a URL using the json api

When working with an external API, I need to access a JSON object from a specific URL. The tutorial for this API provides variables that can be accessed through the URL, but these variables have different names than the attributes of the JSON object. For ...

Have you ever wondered why MEAN.js applications use the #! symbol at the start of their URLs

Embarking on my first MEAN application build using MEAN.JS, I was intrigued by the structure of how mean.js organizes the application, particularly why URLs begin with /#!/. For instance, for the login page, I envisioned: http://example.com/login instea ...

organize a data set using react's hook system

Trying to sort an array using react hooks but the state is not updating. Any help on what could be going wrong? import React, { useState } from "react"; import ReactDOM from "react-dom"; import "./styles.css"; const dogs = [{ name: "fido", age: 22 }, ...

Comparison of Node.js and Express.js APIs for handling responses

Both Node.js and Express.js have their own unique response APIs. Interestingly, there are some similarities between the two, such as: Node.js: response.write(chunk[, encoding][, callback]) Express.js: res.attachment([filename]) res.download(path [, ...

What is the reason for Cloud Firestore's realtime database fetching all items?

Currently, I am developing a project with vuejs and I am facing an issue where I need to fetch only the last created item from Firestore's realtime database. However, when I execute the following code snippet, it retrieves all items from the database ...