Sending parameters to a service's factory

Here is the HTML code I am working with:

  <div class='container-fluid' ng-controller="TypeaheadCtrl">
    <p></p>
    <b>Selected User</b>
    Enter a name: <input type="text" ng-model="selected" typeahead="user as (user.first + ' ' + user.last) for user in users | filter:$viewValue" />
</div>

This is the controller being used:

app.controller('TypeaheadCtrl', ['$scope', 'getUser',function($scope, getUser) { 

  $scope.selected = "";
  getUser.success(function(data) { 
      $scope.users = data; 
  });

}]);

And here is the service implemented:

app.factory('getUser', ['$http', function($http) { 

  return $http.get('https://myUrl?param=Foo') 
            .success(function(data) { 
              return data; 
            }) 
            .error(function(err) { 
              return err; 
            }); 
}]);

I am wondering how I can pass an argument to the service to make the value of param in the URL dynamic.

Answer №1

The most efficient method with minimal alteration is to modify your factory in a way that it returns a function

app.factory('fetchUser', ['$http', function($http) { 

    var httpReq = function(parameter){
        return $http.get('https://myNewUrl?' + parameter + '=Bar') 
            .success(function(response) { 
              return response; 
            }) 
            .error(function(error) { 
              return error; 
            }); 
    }

    return httpReq; 
}]);

You can now input a value into the factory

app.controller('SearchCtrl', ['$scope', 'fetchUser',function($scope, fetchUser) { 

  $scope.selection = "";
  fetchUser('paramInput').success(function(result) { 
      $scope.results = result; 
  });

}]);

Answer №2

A factory is a tool used in programming to create and return objects with publicly available operations. One example of using a factory is to wrap an HTTP call within an object:

app.factory('getUser', ['$http', function($http) { 

    function myInternal(arg1) {
        return $http.get('https://myUrl?param=' + arg1) 
            .success(function(data) { 
              return data; 
            }) 
            .error(function(err) { 
              return err; 
            });
    }
    return {
        makeMyCall: function(arg1) {
            return myInternal(arg1);
        }
    };

}]);

In the controller, you can then call the getUser.makeMyCall function while passing in the necessary argument.

Additionally, if there is no need to manipulate the promise chain, it is not required to handle the success and error functions in the factory:

    function myInternal(arg1) {
        return $http.get('https://myUrl?param=' + arg1);
    }
    return {
        makeMyCall: function(arg1) {
            return myInternal(arg1);
        }
    };

Answer №3

application.controller('TypeaheadController', ['$scope', 'fetchUser',function($scope, fetchUser) { 

  $scope.selectedUser = "";
  fetchUser('Bar').success(function(info) { 
      $scope.allUsers = info; 
  });

}]);


application.factory('fetchUser', ['$http', function($http) { 

  return function(anotherParam) {
      return $http.get('https://differentUrl', {params:{parameter:anotherParam}});      
  };
}]);

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

Executing a callback in AngularJS after multiple HTTP requests have been completed using a forEach loop

I am trying to update multiple items within a foreach loop by sending HTTP requests, and I need a callback once all the requests are complete. Despite searching on Stack Overflow, I haven't found a solution that works for me. Here is the snippet of m ...

NodeJS experiencing a hitch in the image upload process

I am currently working on a Node code snippet that is used for uploading images. The images I am dealing with have sizes ranging from 10 to 200K, so they are relatively small in size. However, the issue I am facing is that Node seems to get stuck process ...

Missing Cookie in request using NodeJS and NextJS

Struggling with integrating cookies in a fullstack app I'm developing using Node for backend and NextJS for frontend on separate servers. The challenge lies in getting the browser to attach the cookie received in the response header from the node serv ...

Is npm installation specifically for a node server?

I'm in the process of developing a React app with webpack and utilizing npm to install different front end packages such as tabs, D3, and more. As I plan for production, I'm wondering if I specifically need to run my server as a Node server given ...

Using MomentJS along with Timezones to accurately display Datetime while accounting for offsets

I am utilizing moment.js along with timezones to generate a datetime linked to a specific timezone: var datetime = moment.tz("2016-08-16 21:51:28","Europe/London"); Due to the recognition of DST (daylight saving time) by this constructor, moment.js will ...

Importing a Vue.js component: Troubleshooting MIME type error

I recently started using Vue.js and decided to try out the https://github.com/olefirenko/vue-google-autocomplete component. I went ahead and downloaded this file from: https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

What is the process of integrating ES6 modules with app.get in a Node/Express routing application?

After researching the benefits of ES6 export, I made the decision to implement it in a NodeJS/Express project instead of using module exports. The MDN documentation explained that export is used as shown below: export function draw(ctx, length, x, y, color ...

Guide to updating the background color of an element with AngularJs when clicked

I've used AngularJS's ng-repeat to display a list of <div> elements. When I select one <div> (div1), its background color changes to blue. If I then click on another <div> (div2), div1's background returns to white and div ...

React testing with Mocha experiencing an Invariant violation

Currently, I am in the process of setting up a React project using Electron. Lately, I have been experimenting with configuring Mocha as my test framework. Everything seems to be working fine when I run: "test": "mocha -w --require babel-core/register ...

Developing with node and express: optimizing your workflow

After researching various blogs and tutorials on node + express development workflow, there is one crucial aspect that seems to be missing: When developing, which version of the app should you have open in your browser? The source app, featuring clean, ...

Utilize HTML, AJAX, and JavaScript to retrieve the location of the current user and display markers for other users on a

I am attempting to display on a single map the current location of a user and markers for other users, whose locations are obtained through an ajax post. In essence, I am looking to merge the concepts from: Google Maps Geolocation Example with: Multiple ...

Why is my Next.js scroll event not triggering when scrolling?

useEffect(() => { document.addEventListener("scroll", ()=> { console.log('.................gotcha'); }); },[]); I am trying to trigger an event when the user scr ...

Is there a way to change a string that says "False" into a Boolean value representing false?

When retrieving values from the backend, I am receiving them as strings 'True' and 'False'. I have been attempting to convert these values into actual Boolean values, however, my current method always returns true. What is the correct a ...

Display the initial three image components on the HTML webpage, then simply click on the "load more" button to reveal the subsequent two elements

I've created a div with the id #myList, which contains 8 sub-divs each with an image. My goal is to initially load the first 3 images and then have the ability to load more when clicking on load more. I attempted to follow this jsfiddle example Bel ...

Understanding this JavaScript code involving shorthand if statements and commas can be achieved by breaking it down step by

Upon encountering this function within the codebase (which is compiled with webpack), my curiosity was piqued and I wanted to delve into its workings. Initially, my eyes fell upon t.length > 100. If it's greater than 100, then the next condition i ...

What is the process for obtaining the number of video views using the YouTube API?

I have a straightforward question: How can I retrieve the number of video views using the YouTube API? Although the task is simple, I need to perform this query on a large number of videos frequently. Is there a way to access their YouTube API in order to ...

Deselect all event listeners excluding the ones specified in Socket.io

I have a node.js application using socket.io to dynamically load external modules, referred to as "activities," in real-time. Each module binds its own events to the sockets, so when switching from one module to another, I need to remove all event listene ...

Guide for using JavaScript to obtain the current line position within a contenteditable div during a keypress event

I am in the process of developing a customized editor using a contenteditable div. I require a javascript code that can determine the line position of the current caret position during a keypress event. It should be able to adapt when new lines are added o ...

Development and staging setups tailored specifically for a JavaScript SDK

Currently, I am working with a Javascript SDK that is available on NPM. Alongside this, I have a Vue application utilizing the SDK and it's crucial for me to test them together across various pre-production environments (such as staging). Here are the ...

What method is the most effective for extracting the first line of a file in Node.js quickly?

If you are faced with multiple lengthy text files and your goal is to extract data solely from the first line of each file (without delving into the rest), how would you recommend achieving this efficiently using Node.js? Appreciate any suggestions! ...