[英]Angular $rootScope.$broadcast not returning
我有Angular Kendo作為UI的AngularJS應用程序。
從一項服務中,我正在向控制器發送廣播。
我正在從服務發送廣播,如下所示:
angular.module('MyAppModule')
.service('MyService', ['$rootScope',function($rootScope)
{
this.MESSAGE = "broadcast_msg";
function sendBroadcast(message, data)
{
console.log("I get this log");
$rootScope.$broadcast(message, data);
console.log("I don't get this log");
}
function onSomeEvent(data)
{
sendBroadcast(MESSAGE, data)
}
}]);
在我的控制器中:
angular.module('MyAppModule')
.controller('MyViewCtrl', ['$scope', 'MyService', function($scope, MyService)
{
function init()
{
$scope.$on(MyService.MESSAGE, function(event, data)
{
if( data.state == "some_state")
{
process()
}
});
}
function process()
{
// Destroy and remove current screen
$("#MyView").data("kendoMobileView").destroy(); // KendoMobileView is provide by Kendo
$("#MyView").remove(); // MyView - is that ID of kendo mobile view
}
}]);
如果我評論destroy
和remove
呼叫,那么一切正常。
但是,當我添加$rootScope.$broadcats
,該服務不會返回。
我需要remove
和destroy
呼叫以清除屏幕和相關狀態。
如何解決這個問題?
更新
我正在從控制器中注銷廣播廣播偵聽器,如下所示。
// While registering listener
var deregisterMessage = $scope.$on(MyService.MESSAGE, function(event, data)
{
});
// At the time of removing screen
if( deregisterMessage != null )
{
deregisterMessage();
deregisterMessage = null;
}
不要$rootScope.$on
控制器中使用$rootScope.$on
,因為即使在控制器銷毀后,事件偵聽器仍然存在,並且會導致內存泄漏。
最好為您需要收聽或廣播的每個事件創建一個服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.