What are some ways to implement a factory function across various AngularJS controllers?

I have a factory function that I need to implement in multiple controllers. The factory code block should be used inside the if condition of one controller and in the else condition of another controller. How can I achieve this using the factory? Any help or guidance on how to accomplish this task would be greatly appreciated.

Below is the code I have tried so far...

Factory.js

angular.module("App").factory('geoTreeFactory', function() {
    return {
        // If block function when conditions are true
        getTreeCheck: function (geoLocation) {
            // Code block for checking tree
        },

        // Else block function when conditions are false
        getTreeUncheck: function(geoLocation) {
            // Code block for unchecking tree
        }
    };
});

Controller.js

var selectedCtlGeoLocations = [];
var selectedCtlGeoLocationIds = [];

$scope.populateControlInPrcsGeoLoction = function(geoLocation) {
    var pos = $.inArray(geoLocation.text, selectedCtlGeoLocations);
    
    if (pos < 0) {
        // Execute If block function of factory
        geoTreeFactory.getTreeCheck();
    } else {
        // Execute Else block function of factory
        geoTreeFactory.getTreeUncheck();
    }
};

Answer №1

Okay, I might be a bit off track here, but is this what you're aiming for?

app.factory('myservice', function(){
  return {
    ifBlock: function(){
      // code to execute if condition is met
    },
    elseBlock: function(){
      // code to execute if condition is not met
    }
  }
});

app.controller('main', function(myservice){
  $scope.myevent = function(geoLocation){
    if(condition){
      myservice.ifBlock(geoLocation);
    } else {
      myservice.elseBlock(geoLocation);
    }
  }
});

You can also address this issue in another way (and based on my interpretation of the problem, this may be the preferred approach):

app.service('myservice', function(){
  return {
    go: function(geoLocation){
      if(condition){
        // code to execute if condition is met
      } else {
        // code to execute if condition is not met
      }
    }
  }
});

app.controller('main', function(myservice){
  $scope.myevent = function(geoLocation){
    myservice.go(geoLocation);
  }
});

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

The duration of user engagement on a website with an embedded iframe

I am working on measuring the time users spend on web pages, excluding the time they navigate away from the browser. While exploring open source libraries like Timejs, I noticed that these tools do not accurately track user time when they are watching vid ...

Executing Javascript and C# functions through a single click

I need to call a method in Javascript and a method in C# when a button is clicked. First, I want to call the C# method called 'Find_Direction' on click, which takes two inputs. Then, I want to call the Javascript method named calcRoute. I attem ...

Building a straightforward RESTful API for user authentication with Node.js, MongoDB, and Express.js

Can someone provide guidance on creating a RESTful API using Node.js, Express.js, and MongoDB? Specifically, I am looking for assistance with writing the schema for login and sign up pages, as well as comparing data in MongoDB using Node.js Express.js. As ...

Hide the Select Column from the material-react-table

Can someone help me with hiding specific columns in the material-react-table component? I've searched the documentation but couldn't find any relevant information. import { useMemo, useState } from "react"; import { MaterialReactTable } ...

Determine the number of Fridays that fall between two dates using JavaScript or jQuery

Can you help me calculate the total number of a specific day between two given dates? For instance, if I have a start date and end date stored in a variable, I would like to know how many Fridays fall within that timeframe. ...

“What could be causing the issue of newly added components not appearing on an extjs panel after removing other components?”

Using ExtJs 6 classic, I have a situation where I am dealing with an Ext.panel.Panel that contains dynamically created child Panels and containers. What I do is save references to these containers and remove them from the parent Panel (this) utilizing the ...

Parameter request shortened

Being new to web application development with express, angular, and mongoose, I am faced with an issue. In my angular controller, I pass the url "/contact/54a153243aac91fc28605b0b", where the last part represents the _id of a record in my mongo database. ...

Troubleshooting custom bower dependency with ng-translate: encountering a 404 error while trying to load the JSON resource

I have successfully implemented a directive using angular-translate with the following configuration: $translateProvider.useSanitizeValueStrategy('escape'); $translateProvider.useStaticFilesLoader({ prefix: 'i18n/messages_', su ...

What is the best way to assign the innerText/innerContent of a list with the values from a multidimensional array?

As a newcomer to JavaScript, I apologize if the code is not up to par. My goal is to allow users to select a state from a form and display 5 cities. This is the current code snippet: HTML with Bootstrap classes <div class="row row1"> <div class= ...

Issue with Date.js: Date.monday() function is not functioning as expected

I am attempting to utilize Datejs for some date functions. However, I am encountering issues with functions like Date.march() and Date.monday(). I have downloaded the necessary files from the Datejs website. Upon inspecting with firebug, it appears that my ...

Execute the JS file to retrieve the initial port available within the npm script

Within my package.json, I have the following script: "dev": "webpack-dev-server --config webpack.dev.js --progress --port ${getPort()}", I've also installed a package called get-port, which allows me to set a default port and ...

Difficulties with toggling jQuery menus

I am trying to create a sidebar that will appear with a full screen fade over the entire page when I click on the 'navigate' text. Currently, the sidebar appears and my header text moves to the left. However, I am struggling to make it responsiv ...

Is fs-extra the best tool for working with a .bundle file?

I am attempting to determine whether a specific folder in my project includes a .bundle file and, if it does, relocate it to another location. If the file is not found, I will use a default option instead. The problem I'm encountering is that I am una ...

Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory - <html> <head> <title>DevOps Monitoring Application</title> <link rel="icon" type="image/png" hr ...

What is the best way to calculate the total of the previous rows in a specific column for each row in a

If you want to check out my problem in action, head over to this fiddle. Here is the code snippet for the HTML: <table ng-app='Payments'> <thead> <tr> <th>Date</th> <th>Cash</th&g ...

Unlocking React Event Handlers using Puppeteer

I'm struggling to fully comprehend my request, and I'm seeking clarification. I am currently working on scraping a website using Puppeteer in NodeJS. So far, I have managed to select the necessary element and access its properties. However, I am ...

React components to separate static PDF pages

I have successfully implemented a feature in my React App that allows me to export a long page in PDF format using html2canvas and jsPDF. The code snippet for exporting the page is as follows: html2canvas(document.body).then((canvas) => { var img ...

Jquery: Retrieving the values from multiple radio button groups

I am encountering an issue with two radio button groups. The val() function is returning inconsistent results, seemingly stuck on an old value. What could be causing this inconsistency? <form id="form_1"> <div id="myForm_1"> <i ...

When attempting to access the Angular app in Edge, it automatically redirects to open in IE 11 instead

I have encountered an issue with my angular 5 App. It works perfectly fine in Chrome and Firefox, but when I try to open it in Microsoft Edge on Windows 10, the application always opens in the IE 11 browser. There are no errors displayed on the console. W ...

Optimized MySQL saving made easy with drag-and-drop functionality

While there have been some similar issues raised on SO, I have already implemented my own solution. However, it may not be considered the ideal approach. The challenge I am facing is that when dragging one element from position 1 to position 50 in a list, ...