Javascript AngularJS在使用控制器作为语法时如何注入依赖项
除了文档中提到的控制器功能之外,我正在重新设计我的一个控制器,以匹配他们建议的语法。但是我不知道如何将$http服务注入我的search()函数中,并且以一种不会被缩小的安全方式注入Javascript AngularJS在使用控制器作为语法时如何注入依赖项,javascript,angularjs,Javascript,Angularjs,除了文档中提到的控制器功能之外,我正在重新设计我的一个控制器,以匹配他们建议的语法。但是我不知道如何将$http服务注入我的search()函数中,并且以一种不会被缩小的安全方式注入 customer.RequestCtrl = function () { this.person = {}; this.searching = false; this.selectedInstitute = null;
customer.RequestCtrl = function () {
this.person = {};
this.searching = false;
this.selectedInstitute = null;
this.query = null;
this.institutes = null;
};
customer.RequestCtrl.prototype.search = function() {
this.searching = true;
this.selectedInstitute = null;
$http({method: 'GET', url: '/api/institutes', params: {q: this.query, max: 250}})
.success(function(data, status, headers, config) {
this.searching = false;
this.institutes = data;
})
.error(function(data, status, headers, config) {
this.searching = false;
this.institutes = null;
});
};
只需插入控制器构造函数,就可以像任何其他属性一样将其作为属性附加到实例
customer.RequestCtrl = function ($http) {
this.person = {};
this.searching = false;
this.selectedInstitute = null;
this.query = null;
this.institutes = null;
this.$http = $http; //Or probably with _ prefix this._http = $http;
};
customer.RequestCtrl.$inject = ['$http']; //explicit annotation
customer.RequestCtrl.prototype.search = function() {
...
this.$http({method: 'GET', url: '/api/institutes', params: {q: this.query, max: 250}})
...
};
另一种方法是添加一个变量并在IIFE中运行控制器防御
(function(customer){
var $httpSvc;
customer.RequestCtrl = function ($http) {
this.person = {};
this.searching = false;
this.selectedInstitute = null;
this.query = null;
this.institutes = null;
$httpSvc = $http;
};
customer.RequestCtrl.prototype.search = function() {
...
$httpSvc({method: 'GET', url: '/api/institutes', params: {q: this.query, max: 250}})
...
};
angular.module('app').controller('RequestCtrl', ['$http', customer.RequestCtrl]);
})(customer);
您还可以尝试在构造函数中声明方法
MyController = function($http) {
this.update = function() {
$http.get(...)
}
}