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?
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.
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
}]);
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With