Angular - 在Controller函数中使用$ http服务

时间:2015-05-23 02:39:02

标签: angularjs angularjs-service

伙计们 - 所以在我持续的Angular冒险中,我遇到了$ http.get对我有用的问题,但$ http.post却没有。它显然是一个范围问题(即我的控制器功能看到' $ http',但其中一个功能不能。到目前为止,这是我的代码:

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

我的HTML页面通过$ http.get方法显示所有记录,但控制器的addDoc'方法(由表单提交触发)导致' $ http未定义'我尝试将数据发布到后端时出错。那么 - 如何将$ http注入我的addDoc方法?

谢谢! 布赖恩

1 个答案:

答案 0 :(得分:1)

如果您真的想使用带有实例方法的控制器,则必须在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>

以下是一些参考资料: