AngularJS如何在使用controller-as语法时注入依赖项

时间:2014-08-27 16:43:16

标签: javascript angularjs

随着文档中提到的控制器一样,我正在重新设计一个控制器以匹配他们建议的语法。但我不确定如何将$ http服务注入我的search()函数,并且以一种安全的方式从缩小中获取?

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

};

2 个答案:

答案 0 :(得分:4)

只需注入您的控制器构造函数,您就可以将其作为属性附加到实例,就像任何其他属性一样。

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

答案 1 :(得分:0)

您也可以尝试在构造函数

中声明方法
MyController = function($http) {
    this.update = function() {
          $http.get(...)
    }
}