我有一个名为 saveInDB 的函数。它将数据保存在数据库中。对象作为参数传递给函数。
$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 访问到其他 Controller 的其他 Controller 中。我没有得到对象。在我有的 Controller 中
var _save = $rootScope.$on('saveCallback',function(){
//i want same obj(which is used for saving ) to be access here.
})
最佳答案
1) 如果您的 Controller 是父子 Controller ,并且您从子 Controller 发出事件 ,您只需要 $emit 事件,父 Controller 只需使用 $on 来监听它。
从子 Controller 发出事件:
$scope.SaveDB(iObj,function(iResult){
$scope.$emit('saveCallback',iResult); //pass the data as the second parameter
});
监听事件(在父 Controller 中):
$scope.$on('saveCallback',function(event,iResult){//receive the data as second parameter
});
2) 如果你的 Controller 是兄弟
从您的 Controller ,您
$emit
事件到父的范围。$scope.SaveDB(iObj,function(iResult){
$scope.$emit('saveCallback',iResult);
});
然后你 parent 的作用域监听这个事件和
$broadcast
它给它的 child 。这个方法可以写在 Angular 模块的 .run
中。堵塞$scope.$on('saveCallback',function (event,iresult){
$scope.$broadcast('saveCallback',iresult);
});
或者您可以将 $rootScope 注入(inject) Controller 并让它 $broadcast 事件:
$scope.SaveDB(iObj,function(iResult){
$rootScope.$broadcast('saveCallback',iResult);
});
对事件感兴趣的范围可以订阅它:
$scope.$on('saveCallBack',function(event, data) {
//access data here
});
关于angularjs - 如何使用 $rootScope 传递对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21346565/