2014-08-27 82 views
4

以下是文檔中提及的控制器特性,我正在修改其中一個控制器以匹配它們所建議的語法。但我不確定如何將$ http服務注入到我的search()函數中,並且可以通過小型化來保證安全?AngularJS如何在使用控制器語法時注入依賴關係

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

}; 

回答

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中運行您的控制器defenision。

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

你也可以嘗試申報內部構造方法

MyController = function($http) { 
    this.update = function() { 
      $http.get(...) 
    } 
} 
相關問題