[英]$broadcast and $on issue when using back button
I have 2 views ('index' and 'item'). 我有2个视图('index'和'item')。
'index' has a button that just go to 'item'. 'index'有一个按钮,只需转到'item'。
'item' has a controller that calls a service that broadcast an event, and the controller keeps listening for this event to fill an object with a value. 'item'有一个控制器,它调用一个广播事件的服务,控制器一直在监听这个事件,用一个值填充一个对象。
Problem : at the first time that I click on the button and I go to 'item', I get the correct object value. 问题 :我第一次点击按钮然后转到'item',我得到了正确的对象值。 However, if I click on back button (returning to 'index') and click on the same button again, I go to 'item' but the object is empty. 但是,如果我单击后退按钮(返回'index')并再次单击相同的按钮,我会转到'item'但对象为空。
MyService 为MyService
update: function() {
$rootScope.$broadcast('event:item-updated');
console.log("broadcast item updated");
return;
}
ItemCtrl ItemCtrl
.controller('ItemCtrl', function($scope, $state, MyService) {
console.log("Item controller");
MyService.update();
$scope.item = {};
$scope.$on('event:item-updated', function(e, status) {
$scope.item = {"name": "My Item"};
console.log("on item updated");
});
}
Index html 索引HTML
<ion-view view-title="Index">
<ion-content>
<div>
<button class="button" ui-sref='app.item'>
Item
</button>
</div>
</ion-content>
</ion-view>
Item html 项目HTML
<ion-view view-title="Item">
<ion-content>
<div>
{{item.name}}
</div>
</ion-content>
</ion-view>
Using some console.log(), I can check that: 使用一些console.log(),我可以检查:
First time: 第一次:
Second time: 第二次:
So, for some reason, the listener is not working when I go to 'item' other times. 因此,出于某种原因,当我在其他时间去“项目”时,听众不工作。
I solved the problem changing the order that I declared the listener and called the server. 我解决了更改我声明监听器并调用服务器的顺序的问题。
.controller('ItemCtrl', function($scope, $state, MyService) {
console.log("Item controller");
$scope.item = {};
$scope.$on('event:item-updated', function(e, status) {
$scope.item = {"name": "My Item"};
console.log("on item updated");
});
MyService.update();
}
So, I should declare the listener before call the service (that broadcast the event). 所以,我应该在调用服务(广播事件)之前声明监听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.