Passing variables from one controller to another with $rootscope

ⅰ亾dé卋堺 提交于 2019-12-11 08:06:35

问题


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');
    });
  }])

回答1:


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;
});


来源:https://stackoverflow.com/questions/23123757/passing-variables-from-one-controller-to-another-with-rootscope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!