我试图使用$ rootscope将id从一个控制器传递到下一个控制器。我认为这就像将变量设置为$ rootscope一样简单,但出于某种原因,当我在控制台中检查时,它会显示为未定义。这个变量不会改变,我希望它变成全球性的#34;对于所有以下控制器。这个没有设置的原因是什么?
.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');
});
}])
答案 0 :(得分:2)
除非你有充分的理由这样做,否则不要使用$ rootScope。在你的情况下没有。改为使用服务
.factory('MyService',function(){
return { myVar1:""};
})
.controller('Ctrl1',function($scope,MyService){
$scope.MyService=MyService;
MyService.myVar1="foo"
})
.controller('Ctrl2',function($scope,MyService){
$scope.MyService=MyService;
});