问题描述
我有一个 HTTP 资源,它从数据库中返回前 10 个实体的 JSON 列表.我这样称呼它:
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 () {
});
}]);
有效!
但是...如何更改 filter
变量以更改查询?我应该重写整个控制器以使其正常工作吗?
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?
抱歉,我的问题不够清晰.当我问这个时,我无法理解 AngularJS 的任何内容.
Sorry for the lack of clarity in my question. When I asked this I couldn't undertand anything of AngularJS.
我的初衷是让变量 $http
注入,而不依赖于为此创建控制器.
My original intent was to get the variable $http
injected, without relying on creating a controller for that.
谢谢大家.
推荐答案
一个可能更好的方法
如果您不想将其放入控制器中,您可以将其注入到配方中(例如,提供者、工厂、服务):https://docs.angularjs.org/guide/providers
myApp.factory('getStuff', ['filter', '$http', function (filter, $http) {
//Blah
}]);
如果您想在任何角度结构之外获取 $http 的实例,您可以执行如下所示的操作.
丹尼斯给出的方法有效;但是,如果在 angular 被引导之前调用它就不起作用.此外,Derek 似乎对 Dennis 的方法有错误,因为他没有 jquery.
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.
Exlord 提到的解决方案更好,因为它没有那个问题,而且更合适:
The solution that Exlord mentioned is better, as it does not have that problem, and is more proper:
$http = angular.injector(["ng"]).get("$http");
说明:
角度注射器是一个:
可用于检索服务以及依赖注入的对象
https://docs.angularjs.org/api/ng/function/angular.injector
函数 angular.injector 将模块作为参数并返回注入器的实例.
The function angular.injector takes the modules as a parameter and returns an instance of the injector.
因此,在这种情况下,您检索 ng 模块(angular 的)的注入器,然后检索服务 $http.
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')
这篇关于Angular.js 从外部控制器调用 $http.get的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!