AngularJS How to introduce dependencies when using a controller - as syntax

Following along with the controller as a function mentioned in the docs, I recycle one of my controllers according to the syntax they proposed. But I'm not sure how to inject the $ http service into my search () function and so that it is safe from minimization?

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
source share
2 answers

Just add a controller to your constructor, and you can attach it to the instance as a property, 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 is to add a variable and start protecting your controller in 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);
+4
source

You can also try to declare methods inside the constructor.

MyController = function($http) {
    this.update = function() {
          $http.get(...)
    }
}
0

All Articles