Andre Soares Andre Soares - 1 month ago 9x
AngularJS Question

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
variable in order to change the query?
Should I rewrite the whole controller to get this to work?


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
injected, without relying on creating a controller for that.

Thanks for everyone.


A likely better method

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");


The angular injector is an:

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

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.

Late for the party: My apologies for reviving a dead question, but I think my answer is useful for others to reference.