Angular.js Call $http.get from outside controller

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 07:57:46

问题


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.


回答1:


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')



回答2:


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.



来源:https://stackoverflow.com/questions/24051335/angular-js-call-http-get-from-outside-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!