Is transferring information to the factory from the controller feasible?

My factory definition:

 myAppServices.factory('ProfileData',['$http',  function($http){
            return{
            newly_joined:function(callback){
            $http.get(
//myUrl will be an url from controller.
                myUrl
            ).success(callback);
              }
    };

          }
                                            ]);

I have three controllers each with a different URL:

Controller 1:

AppControllers.controller('ProfileListCtrl',['$scope','$state', '$rootScope', 'ProfileData', '$timeout',   function($scope, $state, $rootScope, ProfileData, $timeout ) {


    ProfileData.newly_joined(function(response) {
      var myUrl= "www.abc...." 
     //something goes there
});

     }]);

Controller 2:

AppControllers.controller('ProfileListCtrl1',['$scope','$state', '$rootScope', 'ProfileData', '$timeout',   function($scope, $state, $rootScope, ProfileData, $timeout ) {


    ProfileData.newly_joined(function(response) {
      var myUrl= "www.abc...." 
     //something goes there
});

     }]);

And Controller 3:

AppControllers.controller('ProfileListCtrl2',['$scope','$state', '$rootScope', 'ProfileData', '$timeout',   function($scope, $state, $rootScope, ProfileData, $timeout ) {


    ProfileData.newly_joined(function(response) {
      var myUrl= "www.abc...." 
     //something goes there
});

     }]);

I need different data in each controller due to different URLs and I am displaying all three sets of details on a single webpage.

If there is a way to pass the 'myUrl' parameter in the factory so that I can use it for fetching data.

Note: Please refrain from suggesting the usage of $resource or $routeparams as $resource was not effective in retrieving data from JSON and I prefer to avoid using long variable URLs for my page.

Thank you in advance

Answer №1

To enhance the functionality of the newly_joined function, simply include an extra parameter:

newly_joined:function(callback, myUrl){

Furthermore, it is recommended to utilize .then in place of .success for better results.

Answer №2

Your software development team should prioritize implementing promises over using callbacks.

myAppServices.factory('ProfileData',['$http',  function($http){
    return function(myUrl) {
        return $http.get(myUrl);
    };
}]);

The controller

AppControllers.controller('ProfileListCtrl',['$scope', 'ProfileData', function($scope,ProfileData) {

    var myUrl= "www.abc....";
    var httpPromise = ProfileData(myUrl);

    httpPromise.then(function onFulfilled(response) {
        $scope.data = response.data;
    }).catch(function onRejected(response) {
        console.log("ERROR ", response.status);
    });

}]);

View the DEMO on JSFiddle

An added benefit of utilizing promises is their ability to preserve error details.

Note that the factory accepts myUrl as an argument.

To learn more about the benefits of promises over callbacks, check out Why are Callbacks from Promise Then Methods an Anti-Pattern?

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

Styling a textbox within a gridview using JavaScript

Looking for a way to format a textbox within a gridview using JavaScript? Take a look at how the gridview columns are set up: <Columns> <asp:TemplateField> <ItemTemplate><asp:ImageButton runat="server" id="imgbtnEnterAmt" ...

Link directly to a specific slide within the JQuery Revolution Slider

I have integrated the JQuery revolution slider into my website and it's working well. However, I am looking for some guidance on how to link to a specific slide within the slider. My goal is to have the slider scroll to a particular slide when a user ...

Activate the "order evaluation" trigger on the checkout page in Woocommerce

I have implemented the Woocommerce Advanced Shipping plugin created by Jeroen Sormani for managing shipping methods, along with the WooCommerce Pay for Payment plugin developed by Karolína Vyskočilová to add a fixed €5 fee to the "cash on delivery" pa ...

LocalStorage is designed to hold only the most recent data input

As I work on developing an app using PhoneGap for iOS, I encounter an issue with LocalStorage. After entering and storing a username and password on my iPad, I close the app, open it again, and enter a new set of login credentials. However, when inspecting ...

Interactive ng-messages and validation

Validation rules have been set in JSON format and are stored within a factory service. "inputname":{ "rule":{ "required":"required", "ng-minlength":"3", "ng-maxlength":"16" }, "error":{ "required":"Name ...

Tips for implementing the datatable method on a dynamically generated table

I have a scenario where I need to dynamically create a table by triggering a button click event. function populateTable() { $.ajax ({ url: 'php/GetData.php', type: 'POST', data: {id:25}, success: f ...

Assigning a value to an input field using jQuery

I'm facing an issue while trying to set the value for an input using jQuery. Essentially, when you click on a link, it redirects you to a different page with a form, and I am attempting to set the value of one of the inputs in that form. Unfortunately ...

I have a JavaScript code that smoothly scrolls to different id's on a webpage, but I need assistance in adding an exception for a particular id

I'm looking to incorporate smooth scrolling for all hash links in my JavaScript. However, I need the id=nav and its resulting hash link, /#nav, to be exempt from this functionality as it interferes with the menu responsiveness. Can someone provide gui ...

Arranging a list based on the child property in a React component

Within my application, I have an array mapped to a map that generates a div with a data-date attribute as shown below: It's worth noting that the array cannot be sorted here since there are no dates available for comparison, only the element ID cons ...

Verifying Angular JS Routing: Ensuring the Current URL Matches the Route, including Dynamic URL Parameters

Just setting this up: app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/asd/:id/:slug',{ templateUrl:'views/home/index.html', controller:'Home', publicAccess:true, se ...

Troubles with IE7 regarding jQuery [clicking and changing events]

My code snippets are designed to loop through cached JSON data on the 1st click function and display any values that exist for a specific id. The 2nd change function captures when elements' values change (e.g., from yes to no). Since these elements a ...

When the mouse is released, modify the button

Looking for assistance with changing the background color of a button when clicked, without any post back. I have multiple buttons and want only the clicked one to change color while the others stay the same. Any suggestions on how to achieve this? ...

Exploring the Diversity of Forms with Ajax and JQuery

$(document).ready(function () { $("#addrow").click(function () { var newRow = '<tr><td><input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]"></td><td><input type="text" ...

dividing the content of a division into sections similar to a PDF file

I am currently working on a resume application and I am looking for a way to display the HTML preview of the resume in multiple divs or automatically insert a horizontal row if the content exceeds the height of the div. The goal is to make it look like sep ...

Add a color gradient to text as it animates without displaying any code tags (HTML, CSS, JS)

I have a unique text animation that loads when the page loads. The characters will be gradually written to the screen with some words having a gradient effect. While I've managed to successfully apply the gradient, there seems to be a pause when it re ...

Applying a custom class to a particular row in an AngularJS datatable using the created

I am currently working with AngularJS datatables and I want to apply a custom class to a row if a specific condition is met. Here's what I have attempted so far: this.dtOptions = DTOptionsBuilder.newOptions() ... .withOption('createdRow', f ...

Tips for designing a button that can execute a JavaScript function repeatedly

My goal is to rotate the numbers clockwise when the rotate button is clicked. I have included all the relevant code. I have created a button that triggers a javascript function when clicked. The problem is that the function only rotates the numbers once. ...

Difficulty encountered when positioning a container using BootStrap 4

As a newcomer to the world of web development, I encountered an issue while trying to align a container on my webpage. Despite my efforts to center the container using (line 30), the page seems to update but there is no visible change. Can anyone help me ...

Return a response from the controller method without using the express response object

When attempting to handle the scenario where a fetch for an item does not return anything from another method that lacks the express response, I encounter an issue. I invoke this method from another one that has the express response: const updateItem = asy ...

What is the connection between the server and client logins?

After setting up a MEAN stack based on http://mean.io, I successfully got it running but am now struggling with the user authentication flow. The confusion lies in the distinction between server/views and public/views. I know that for requiring user auth ...