Search code examples
javascriptangularjsservicecontrollerrootscope

$rootScope and passing data from controller to service


I'm using angular js and have got a controller looking like this

myApp = angular.module("myApp.controllers", []);
myApp.controller("ScheduleCtrl", function($scope, $http, ScheduleService){
    $scope.hours = 4;
    ScheduleService.test();
    ScheduleService.initializeSchedule();
});

and a service (in another file) looking like this

myApp = angular.module('myApp.services', []);
myApp.factory('ScheduleService', ['$rootScope', function($rootScope){

    return {
        test : 
            function(){
                alert("Test");
            },
        initializeSchedule : 
            function(){
                alert($rootScope.hours);
            }
    };
});

To assure everyone that things are hooked up properly from service to controller, the first call to "test()" inside my controller produces the desired output in the alert box. However, for the next function, which as of now should be alerting "4", is instead alerting "undefined".

How can I use either $rootScope or something else in order to utilize scope variables to my service.


Solution

  • You need to inject $rootScope into your controller and use $rootScope instead of $scope. DEMO

    myApp.controller("ScheduleCtrl", function($scope, $rootScope, $http, ScheduleService){
        $rootScope.hours = 4;
        ScheduleService.test();
        ScheduleService.initializeSchedule();
    });
    

    But in this case you don't need to use $rootScope. You can just pass data as parameter into service function.

    return {
        test : 
            function(){
                alert("Test");
            },
        initializeSchedule : 
            function(hours){
                alert(hours);
            }
    };