Search code examples
angularjsservicecontrollerangularjs-scoperootscope

How do you set $rootScope within Angular Service function?


I'm having trouble setting $rootScope for Angularjs.

Below is my function

App.controller('Controller',
function (UtilityService, $rootScope) {

var setSession = function () {

  $rootScope.test = "yes"; // <-- I get this

  UtilityService.getSession().success(
  function () {       
    $rootScope.test = "No"; // <-- I don't get this How do I get/set this value?       
  });      
};

setSession();   

});

Additional Info:

One of the ways that might work is to set up a service that is interacted between multiple controllers. Does anybody know how to do this with the service returning an http.get json object.

I'm having trouble getting a dynamic scope in my controller that is instantiated within a service.


Solution

  • In order to address my issue I had to

    1) Pass $rootScope into my 2nd controller

    App.controller($rootScope) {

    2) Set my 2nd controller's function to $rootScope

    $rootScope.functionCall = function () {};

    3) Set my passed value to $rootScope ($rootScope.orderId)

    $rootScope.functionCall = function () {
     Service.getItems($rootScope.orderId).success(
        function(results) {
          $scope.items = results;
        });
    };
    

    4) within my utility controller, I loop through my results, parsing them, and setting them to $rootScope as you can see in #3 I am initializing "$rootScope.orderId"

    angular.forEach(results, function (value, key) {
          if (key != null) {
            $parse(key).assign($rootScope, value);
          }
        });   
    

    5) I am re-calling the controller's function from within my service call! This is what did the magic for me putting my variable "in scope"

    $rootScope.functionCall();

    6) I am also testing to see if the function exist cause different pages utilize the utility code but may not have the function to execute

    if (typeof $rootScope.functionCall == 'function')

    var setSession = function () {
    
      UtilityService.getSession().success(
      function (results) {             
    
        // Place the rootscope sessions in scope
        angular.forEach(results, function (value, key) {
          if (key != null) {
            $parse(key).assign($rootScope, value);
          }
        });                
    
        // Have to bypass "scope" issues and thus have to execute these fns()
        if (typeof $rootScope.functionCall == 'function') {
          $rootScope.functionCall();
        }
    
    });
    
    };
    setSession();