如何使用 $rootScope 传递对象? [英] How to pass an object using $rootScope?

查看:22
本文介绍了如何使用 $rootScope 传递对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 saveInDB 的函数.将数据保存在数据库中.对象作为参数传递给函数.

I have one function named as saveInDB. Which saves data in the Database. Object is passed as a parameter to the function.

$scope.SaveDB(iObj,function(iResult){
//after a sucessfull opreation in the DB. Now  I need iObj to be passed to other controller.
// I have used $emit method
$rootScope.$emit('saveCallback');
})

在其他控制器中,我需要将 iObj 访问到其他控制器.我没有得到对象.在控制器中我有

In other controller where I need to access the iObj to other controllers. I am not getting the object. In a controllers I have

var _save = $rootScope.$on('saveCallback',function(){
//i want same obj(which is used for saving ) to be access here.
})

推荐答案

1) 如果您的控制器是父子控制器,并且您从子控制器发出事件,您只需要$emit 事件,父控制器只是使用 $on 来监听它.

1) If your controllers are parent-child, and you're emitting the event from the child controller, you just need to $emit the event and the parent controller just uses $on to listen to it.

从子控制器发出事件:

$scope.SaveDB(iObj,function(iResult){
  $scope.$emit('saveCallback',iResult); //pass the data as the second parameter
});

监听事件(在父控制器中):

Listening to the event (in parent controller):

$scope.$on('saveCallback',function(event,iResult){//receive the data as second parameter

});

2) 如果你的控制器是兄弟

从你的控制器,你$emit事件到父级的作用域.

From your controller, you $emit the event to the parent's scope.

$scope.SaveDB(iObj,function(iResult){

   $scope.$emit('saveCallback',iResult);
});

您的父级作用域会侦听此事件并将其$broadcast 发送给其子级.这个方法可以写在 angular 模块的 .run

Your parent's scope then listens to this event and $broadcast it to its children. This method could be written inside angular module's .run block

$scope.$on('saveCallback',function (event,iresult){
    $scope.$broadcast('saveCallback',iresult);
});

或者你可以将 $rootScope 注入控制器并让它 $broadcast 事件:

$scope.SaveDB(iObj,function(iResult){
   $rootScope.$broadcast('saveCallback',iResult);
});

对事件感兴趣的范围可以订阅它:

The scopes interested in the event can subscribe to it:

$scope.$on('saveCallBack',function(event, data) {
   //access data here 
});

这篇关于如何使用 $rootScope 传递对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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