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

查看:106
本文介绍了如何使用$ 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侦听其子级.该方法可以写在角度模块的.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注入到控制器中并使其广播事件:

$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天全站免登陆