Search code examples
angularjsangularjs-service

Angular - Using $http Service in Controller Function


folks-- so in my continuing Angular adventures, I've run into an issue where $http.get is working for me, but $http.post is not. It's obvivously an issue of scope (i.e., my controller function sees '$http', but one of its functions cannot. Here's my code so far:

var app = angular.module('docManager', []);
app.controller('DocManCtrl', ['$http', DocManCtrl]);

function DocManCtrl($http){
  var self = this;
  $http.get('http://localhost:3000/documents').success(function(data){
    self.documents = data;
    }).error(function(){
    console.log('Error: could not GET documents');
  });
}

DocManCtrl.prototype.addDoc = function(){
  var self = this;
  self.documents.push({filename: this.filename, category: this.category});
  $http.post('http://localhost:3000/documents', self.documents).success(function(data){
  console.log('document posted.');
  }).error(function(){
  console.log('document not posted');
  });
};

My HTML page displays all the records via the $http.get method, but the controller's 'addDoc' method (triggered by a form submit) is causing a '$http not defined' error when I try to post data to my backend. So-- how can I get $http injected into my addDoc method?

Thanks! Bryan


Solution

  • If you really want to use controllers with instance methods, you have to create a reference to the injected services on self:

    var app = angular.module('docManager', []);
    app.controller('DocManCtrl', ['$http', DocManCtrl]);
    
    function DocManCtrl($http) {
      var self = this;
      self._http = $http; // <== For use in instance methods.
    
      self.documents = [];
      $http.get('http://localhost:3000/documents').success(function(data) {
        self.documents = data;
      }).error(function() {
        console.log('Error: could not GET documents');
      });
    }
    
    DocManCtrl.prototype.addDoc = function() {
      var self = this;
      self.documents.push({
        filename: this.filename,
        category: this.category
      });
      self._http.post('http://localhost:3000/documents', self.documents).success(function(data) {
        console.log('document posted.');
      }).error(function() {
        console.log('document not posted');
      });
    };
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <div ng-app='docManager' ng-controller='DocManCtrl as vm'>
      <button ng-click="vm.addDoc()">Add Doc</button>
    </div>

    Here are some references: