项目中遇到的关于兄弟controller之间传值的问题解决

时间:2023-03-08 20:43:12

层级关系如下

<ons-page ng-controller="tabbarIndexController">
<ons-tabbar position="top" var="tabbar">
<ons-tab label="新建消息" page="pages/newMsg.html" active="true"></ons-tab>
<ons-tab label="历史消息管理" page="pages/historyMsg.html"></ons-tab>
</ons-tabbar>
</ons-page>

项目需求是,在历史消息管理页面的消息列表中通过点击事件将get到的消息详情填充到新建消息页面,即将historyMsgController中的数据传给newMsgController,解决如下:

思路1:在historyMsgController中用$scope.$emit将数据发送给父级的tabbarIndexController,父级用$on接受数据后再用$scope.$broadcast广播给子级的newMsgController,子级再用$on接收。

思路2:在historyMsgController中用$scope.$parent.$emit直接利用父级scope来$scope.$broadcast广播给子级的newMsgController,子级用$on接受。

但是由于项目的特殊性,onsenui的ons-tabbar组件存在多级分层,所以思路2不适用;其次,要注意的是在onsenui中,ons-tabbar在切换中会删除切换之前的ons-page,即:

当切换至新建消息tab页时DOM节点中只有新建消息的ons-page项目中遇到的关于兄弟controller之间传值的问题解决

反之,项目中遇到的关于兄弟controller之间传值的问题解决

所以当页面处于历史消息管理tab页,此时是DOM树中是没有新建消息页面的,虽然可以从父级中广播数据到子级,但新建消息页面此时是无法接受到的,所以思路1不适用与此项目

思路3:在父级控制器中:

$scope.parentobj={};
$scope.parentobj.historyMsgData=null; //用于接收子级historyMsgController中的数据

    在historyMsgController中:

    msgDetails(messOne:any){                                        //单击消息详情展示消息和编辑消息按钮
let $scope = this.$scope;
let $log = this.$log;
let $window=this.$window;
let newMsgService = this.newMsgService;
let messOneId:any = messOne;
newMsgService.messageDetails(messOneId).then((response) => {
if (response["status"] === 200) {
$log.debug(response);
$scope.msgData= response["data"]; //先存储response中的data
$scope['parentobj'].historyMsgData=$scope.msgData; //把消息数据保存进父级的变量
console.log($scope['parentobj'].historyMsgData);
$window.tabbar.setActiveTab(0);
}
}, (error) => {
$log.debug("failure");
});
}

    此时,父级中的$scope.parentobj.historyMsgData已经存储了response["data"]。

    接着,在newMsgController中用一个变量接收父级的$scope.parentobj.historyMsgData,直接使用就好了!

$scope.historyMsgData=$scope['parentobj'].historyMsgData;