我试图在角度控制器之间共享一个id
我创建了如下服务:
app.factory("idService",function() { var id; addId = function(id) { id = id; }; getId = function() { return id; }; });
在我的控制器中,我试图使用此服务如下:
app.controller('photoFormController',['$scope','$http','idService',function($scope,$http,idService) { $scope.id = idService.getId(); }]);
我收到一个错误,无法调用未定义的方法,显然我注入了错误的服务.有人可以帮忙吗?
编辑:
根据下面的解决方案,该服务不再生成错误,但是我无法恢复id变量,我可以看到它是从一个控制器设置的,但在检索时它仍未定义:
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 }; });