4

Following along with the controller-as feature mentioned in the docs, I'm reworking one of my controllers to match the syntax they suggested. But I'm not sure how to inject the $http service into my search() function, and in a way that will be safe from minification?

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

};
Nicholas Hirras
  • 2,592
  • 2
  • 21
  • 28

2 Answers2

4

Just inject in your controller constructor, and you can attach it to the instance as a property just like any other property.

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

Another way would be add a variable and run your controller defenision in an 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);
PSL
  • 123,204
  • 21
  • 253
  • 243
0

Also you could try to declare methods inside constructor

MyController = function($http) {
    this.update = function() {
          $http.get(...)
    }
}
syabro
  • 1,857
  • 2
  • 15
  • 30