Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js Call $http.get from outside controller

I have an HTTP resource that returns a JSON list of top 10 entities from a database. I call it this way:

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 () {
        });
    }]);

It works!

But... how can I change the filter variable in order to change the query? Should I rewrite the whole controller to get this to work?

Update

Sorry for the lack of clarity in my question. When I asked this I couldn't undertand anything of AngularJS.

My original intent was to get the variable $http injected, without relying on creating a controller for that.

Thanks for everyone.

like image 378
Andre Soares Avatar asked Jun 05 '14 03:06

Andre Soares


2 Answers

A likely better method

If you don't want to get it inside a controller, you could have it injected into a recipe (ex, provider, factory, service): https://docs.angularjs.org/guide/providers

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

If you want to get an instance of $http outside of any angular struct, you can do what's shown below.

The method given by Dennis works; however, it does not work if called before angular has been bootstrapped. Also, it seems like Derek has an error with Dennis' method because he does not have jquery.

The solution that Exlord mentioned is better, as it does not have that problem, and is more proper:

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

Explained:

The angular injector is an:

object that can be used for retrieving services as well as for dependency injection

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

The function angular.injector takes the modules as a parameter and returns an instance of the injector.

So in this case you retrieve an injector for the ng module (angular's), and then retrieve the service $http.

Note: One thing to keep in mind when using injector like this is that in my own findings it seems you need to make sure you include modules in the inject which what you are "getting" will need. For example:

angular.injector(['ng', 'ngCordova']).get('$cordovaFileTransfer')
like image 102
csga5000 Avatar answered Nov 11 '22 03:11

csga5000


Regarding to your question "... call $http.get from outside controller" you can do the following:

... ANYWHERE IN YOUR CODE

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

ANYWHERE IN YOUR CODE ...

See official docs from angular: angular $injector docs : The get(name); method Returns an instance of the service.

like image 8
Dennis Ahaus Avatar answered Nov 11 '22 02:11

Dennis Ahaus