Using Angular.js to Make a $http.get Request from a Different Controller

I am utilizing an HTTP resource that provides a JSON list of top 10 entities from a database by calling it in this manner:

var filter= "john";
var myApp = angular.module('myApp', []);
myApp.controller('SearchController', ['$scope','$http', function ($scope, $http) {
    $http.get('/api/Entity/Find/' + filter). //Get entities filtered
        success(function (data, status, headers, config) {
            $scope.entities = data;
        }).
        error(function () {
        });
    }]);

This method works seamlessly!

However, I am now wondering how I can manipulate the filter variable to modify the query. Do I need to completely overhaul the controller for this adjustment?

Update

Apologies for the unclear nature of my initial question. At the time of asking, I had limited knowledge of AngularJS.

The main goal was to inject the variable $http without having to rely on creating a new controller solely for this purpose.

Thank you to everyone for their assistance.

Answer №1

An improved approach to fetching data

If retrieving data outside of a controller is your preference, you can inject it into a recipe (such as provider, factory, or service): https://docs.angularjs.org/guide/providers

myApp.factory('getStuff', ['filter', '$http', function (filter, $http) {
    //Blah
}]);

To obtain an instance of $http without being within an angular structure, follow the example below.

The method provided by Dennis functions correctly; however, calling it before angular bootstraps may cause issues. Also, Derek encountered errors with Dennis' method due to a missing jquery dependency.

The solution suggested by Exlord is more reliable and avoids such problems:

$http = angular.injector(["ng"]).get("$http");

Explanation:

The angular injector is:

An object used for accessing services and performing dependency injection

https://docs.angularjs.org/api/ng/function/angular.injector

The angular.injector function takes modules as input and returns an injector instance.

In this context, an injector for the ng module (angular's module) is retrieved, followed by retrieving the $http service.

Note: When using the injector in this manner, ensure that the necessary modules are included in order to retrieve the desired dependencies. For example:

angular.injector(['ng', 'ngCordova']).get('$cordovaFileTransfer')

Answer №2

Answering your query on how to "execute $http.get from an external controller", you can implement the following approach:

... ANYWHERE IN YOUR CODE

var $http = angular.element('html').injector().get('$http');
$http.get(...).success(...);

ANYWHERE IN YOUR CODE ...

For more information, refer to the official Angular documentation: angular $injector docs : The get(name); method

Returns an instance of the service.

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

Confirm Form using AngularJS Once Enter is Pressed

Within my AngularJS code, I have a field description: input.form-control(type='password' placeholder='password' id='passwordInput' name='passwordInput' ng-model=' ...

Tacking the progress bar onto an array of $.ajax() calls within a Promise.all

FINAL UPDATE 25/06/20: After a thorough investigation, I discovered the root causes of why the progress bar was not functioning as intended. Firstly, dealing with $.ajax() proved to be cumbersome due to its lack of proper promise handling. To resolve this ...

What is the best way to pass the setState value to the useEffect hook?

After watching a Youtube video, I took on the challenge of creating my own recipe app using React.js as a beginner. I have been troubleshooting for the past 2 days and seem to have hit a roadblock. The issue lies in passing the value of my state to the use ...

Is it possible that an issue with ui-router is causing Angular to crash Chrome on a local machine?

Encountering a peculiar issue with AngularJS in a local Windows environment. Utilizing two Angular-based bootstrap frameworks, Homer and Neuboard (links: homer and neuboard). Running both templates on Chrome locally causes the browser to freeze and consume ...

React-Router failing to properly unmount components when the location parameter changes

I'm struggling with a frustrating issue - I have a simple app created using create-react-app and I'm utilizing React-Router. JSX: <Router> <Route path="/pages/:pageId" component={Page} /> </Router> Within the Page ...

Issue: The variable THREE has not been defined within the FBXLoader code

Currently, I am utilizing the module version of three.js in order to execute imports from a client-side JavaScript file structure. The core functionality of THREE is working correctly. However, I am encountering an issue when attempting to use it with FBX ...

What is the best way to assign specific codes to separate pages using a single JS file?

I am currently working on a project that involves an authentication JavaScript which is responsible for managing user sign-ins and registrations. However, there are certain lines of code within this script that impact different pages in various ways. I n ...

No data, response or issue received from the Internet API

In my web api project, I have created the following controller: public IEnumerable<Speciality> GetAllSpecialities() { List<Speciality> specialities = null; try { specialities = (new Datatable(Proper ...

Verify whether an option is chosen in CakePHP 3 form

I'm working on a form where users can select Types and each type has an associated color. In my TypesController, I have a function that retrieves the list of types with their IDs, names, and colors. $types = $this->Types->find('list') ...

Delete the content on a webpage using an Ajax jQuery request to transfer it elsewhere

Whenever I submit a form using an ajax post request, I receive values from the controller and manipulate the page based on those values. However, my issue is that I need to erase the values from the previous request when the form is submitted again. For in ...

How can the color of the <md-toolbar> be customized?

Here is a glimpse of how my code appears on CodePen: I am aiming to have the background color of "Sidenav Left" match that of "Menu Items", which is designated by the class .nav-theme { background-color: #34495E } I attempted to override it like this ...

Struggling to run npm build in Next.js project due to webpack errors?

After months of developing this application, I encountered a frustrating error when attempting to run npm run build for the first time today. Despite removing next-transpile-modules from my next.config.js and taking various troubleshooting steps like delet ...

What is the best way to extract hover-box information from an ajax website with Python?

Attempting to extract the dimensions for each cell on a map from this AJAX site, where details only appear when hovering over the cells has proven unsuccessful so far. Using Python selenium webdriver and phantomJS did not yield any data when trying to loa ...

How can the checkers code be corrected due to a mistake?

Designed a simple game where the objective is to clear all the pieces by jumping over the checkers. However, encountering an error when attempting to remove the checker for the second time. Uncaught TypeError: Cannot read property 'theRow' of u ...

The some() method in Javascript with an extra argument

I want to validate if at least one element in an array satisfies a certain condition. The condition is based on a variable. Here's an example of how I'm currently attempting this: function checkCondition(previousValue, index, array) { retur ...

Struggling with incorporating a button into a ReactJS table

I am trying to display a (view) button in the table, but I encountered the following error: Module parse failed: Unexpected token < in JSON at position 165 while parsing near '...2021", "view": <button type="submit...' You m ...

Video not updating with new source URL

I am currently facing an issue when attempting to assign a source to a video in AngularJS. Below is the HTML code for the view: <div class="row"> <div class="col-lg-10 col-lg-offset-1"> <video width="100%" controls> < ...

What is the procedure for extracting both the previous and updated values from the dynamic autocomplete feature when utilizing md-selected-item-change in Angular Material?

Currently, I'm working with Angular Material's autocomplete feature and am interested in retrieving the previous value when an item is changed. Due to the dynamic addition of the autocomplete directive on the web page, utilizing $watch threads m ...

Utilize v-for to dynamically showcase a variety of images on your

My goal is to showcase several JPG pictures located in the src/assets/images folder by utilizing the v-for directive. However, it seems like the browser is having trouble locating them. Interestingly, manually adding the pictures with the same paths works ...

Switching from an AJAX GET request to a POST request involves updating the

I have been trying to figure out how to convert my AJAX GET query to POST by reading forums and searching on Google, but I am still confused. If someone could assist me with this, it would be greatly appreciated. Thank you! Here is the code snippet I am w ...