我正在尝试在 Angular Controller 之间共享 id
我创建了一个服务,如下所示:
app.factory("idService", function() {
var id;
addId = function(id) {
id = id;
};
getId = function() {
return id;
};
});
在我的 Controller 中,我尝试按如下方式使用此服务:
app.controller('photoFormController', ['$scope', '$http', 'idService' , function($scope, $http, idService) {
$scope.id = idService.getId();
}]);
我收到无法调用未定义方法的错误,显然我错误地注入(inject)了服务。有人可以帮忙吗?
编辑:
基于下面的解决方案,该服务不再生成错误,但是我无法取回 id 变量,我可以看到它是从一个 Controller 设置的,但是在检索时它仍然未定义:
app.factory("idService", function() {
var id;
addId = function(id) {
id = id;
console.log("added id of: " + id);
};
getId = function() {
console.log("trying to return : " + id);
return id;
};
return {
addId: addId,
getId: getId
};
});
最佳答案
您需要在工厂
内返回一个对象。这个返回的对象是您的服务实例:
app.factory("idService", function() {
var _id; //use _id instead to avoid shadowing your variable with the same name id
var addId = function(id) { //use var to avoid creating a property on the global object
_id = id;
};
var getId = function() { //use var to avoid creating a property on the global object
return _id;
};
return {
addId : addId ,
getId : getId
};
});
关于angularjs - angular.service ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23058992/