[英]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.