Mr. BigglesWorth
Mr. BigglesWorth

Reputation: 1540

Passing variables from one controller to another with $rootscope

I'm trying to pass the id from one controller onto the next using $rootscope. I thought it was as simple as setting the variable to $rootscope, but for some reason when i check in console it comes up as undefined. This variable will not change and i'd like to have it be "global" for all following controllers. Any reason why this isn't getting set?

  .controller('CubeHeadCtrl', ['$scope',  '$rootScope', '$stateParams', 'cubeHeadFactory', 'localUserFactory', '$q',  function($scope, $rootScope, $stateParams, cubeHeadFactory, localUserFactory, $q) {

    cubeHeadFactory.get({ urlName: $stateParams.urlName }, function(data){
      $scope.cube = data;
      $rootScope.home_channel_id = $scope.cube.home_channel_id;
    });
  }])


  .controller('CubeLiveCtrl', ['$scope', '$rootScope', '$stateParams', 'cubeHeadFactory', 'cubeLiveFactory',  function($scope, $rootScope, $stateParams, cubeHeadFactory, cubeLiveFactory) {
    $scope.homeid = $rootScope.home_channel_id;

        cubeLiveFactory.query({dynamicChannelID: $scope.homeid}, function(data){
           $scope.cubeLive = data;
           console.log('This is there we check out the ID with = ' +$scope.homeid+ ' isnt that nice');
    });
  }])

Upvotes: 1

Views: 1109

Answers (1)

mpm
mpm

Reputation: 20154

dont use $rootScope unless you have a pretty good reason to do so.in your case there is none. Use services instead

.factory('MyService',function(){
    return { myVar1:""};
})
.controller('Ctrl1',function($scope,MyService){
    $scope.MyService=MyService;
    MyService.myVar1="foo"
})
.controller('Ctrl2',function($scope,MyService){
    $scope.MyService=MyService;
});

Upvotes: 2

Related Questions