使用 $rootscope 将变量从一个控制器传递到另一个控制器 [英] Passing variables from one controller to another with $rootscope

查看:44
本文介绍了使用 $rootscope 将变量从一个控制器传递到另一个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 $rootscope 将 id 从一个控制器传递到下一个控制器.我认为这就像将变量设置为 $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');
    });
  }])

推荐答案

不要使用 $rootScope 除非你有很好的理由这样做.在你的情况下没有.改用服务

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

这篇关于使用 $rootscope 将变量从一个控制器传递到另一个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆