angularjs - angular.service

标签 angularjs service factory

我正在尝试在 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/

相关文章:

linux - 使 Linux 'service' 在服务器重新启动时自动启动

android - 我的应用程序中哪个更好?IntentService 或 Service?

java - 在 Android 编程中使用与在 Java 编程中相同的方法是否有意义?

design-patterns - 工厂与原型(prototype) - 什么时候使用?

javascript - 在1个项目中制作2个模块

javascript - AngularJS it() 和 describe() 函数的目的是什么?

angularjs - 不使用全局变量的 angular.factory 中 $resource 的动态 URL

forms - ZF2 - 工厂调用创建的表单需要传递给服务的 url 参数

javascript - 添加 office.js 禁用 html5mode

javascript - 函数 "cancel"添加编辑的表单而不是取消它