AngularJS - 访问控制器中定义的服务中的var

时间:2014-09-03 10:20:14

标签: angularjs angularjs-scope angular-services

我有一个角度控制器,它有许多变量被decalred。我试图在我的角度服务中访问这些:

app.controller("MyController", function($scope, myService) {

    var pageIDs = {
        '1': 'home',
        '2': 'contact-us',
        '3': 'products',
        '4': 'complaints'
    }

    var doSomething = {
        'home': function () {
            $scope.Model($scope.MyData, {
                Data: $scope.Data
            });
        },
        // Contact-us function ////////
        // Products functions ////////
        // Complaints functions ////////
    }

    $scope.service = myService.getData;
}

app.factory('myService', function() {
    return {
        getData: function() {
            var Hash = window.location.hash;
            if (Hash) {
                var WithoutHash = WithHash.substring(1);
                if (doSomething [WithoutHash]) doSomething [WithoutHash]();
            }
        }
     };
 });

正如您所看到的,在myService中,我正在尝试访问在我的控制器中定义的var doSomething。

2 个答案:

答案 0 :(得分:1)

将所有变量放在$ scope或任何对象中并传递服务方法,如下所示:

app.controller("MyController", function($scope, myService) {

            $scope.pageIDs = {
                '1': 'home',
                '2': 'contact-us',
                '3': 'products',
                '4': 'complaints'
            }

            var doSomething = {
                'home': function() {
                    $scope.Model($scope.MyData, {
                        Data: $scope.Data
                    });
                },
                // Contact-us function ////////
                // Products functions ////////
                // Complaints functions ////////
            }

            $scope.service = myService.getData;
            myService.setData($scope);

        }

        app.factory('myService', function() {
            var controllerVar = {};
            return {
                getData: function() {
                    var Hash = window.location.hash;
                    if (Hash) {
                        var WithoutHash = WithHash.substring(1);
                        if (doSomething[WithoutHash]) doSomething[WithoutHash]();
                    }
                }
                setData: function(obj) {
                    controllerVar = obj;
                }

            };
        });

答案 1 :(得分:1)

您可以将变量提供给服务:

$scope.service = myService.getData(doSomething);

并在您的服务中:

app.factory('myService', function() {
    return {
        getData: function(doSomething) {
            var Hash = window.location.hash;
            if (Hash) {
                var WithoutHash = WithHash.substring(1);
                if (doSomething [WithoutHash]) doSomething [WithoutHash]();
            }
        }
    };
});