Angularjs 角度-在控制器函数中使用$http服务
伙计们——在我继续的角度冒险中,我遇到了一个问题,$http.get对我有效,而$http.post对我无效。很明显,这是一个范围问题(即,我的控制器函数可以看到“$http”,但它的一个函数不能看到。以下是我目前的代码:Angularjs 角度-在控制器函数中使用$http服务,angularjs,angularjs-service,Angularjs,Angularjs Service,伙计们——在我继续的角度冒险中,我遇到了一个问题,$http.get对我有效,而$http.post对我无效。很明显,这是一个范围问题(即,我的控制器函数可以看到“$http”,但它的一个函数不能看到。以下是我目前的代码: var app = angular.module('docManager', []); app.controller('DocManCtrl', ['$http', DocManCtrl]); function DocManCtrl($http){ var self =
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方法
谢谢!
Bryan如果您真的想将控制器与实例方法一起使用,您必须在self上创建对注入服务的引用:
var-app=angular.module('docManager',[]);
app.controller('DocManCtrl',['$http',DocManCtrl]);
函数DocManCtrl($http){
var self=这个;
self.\u http=$http;//一个更干净的解决方法是不使用控制器上的原型,并将addDoc中的逻辑移动到一个注入了$http的服务中,而不是处理范围问题,这可能更类似于您在web上看到的其他角度代码。