在 $location.path() 更改后的另一个 ng-view 中触发事件

Trigger event in another ng-view after $location.path() has changed

本文关键字:ng-view 另一个 事件 location path      更新时间:2023-09-26

我想在 $location.path() 更改 ng-view(不使用 $rootScope)后在另一个视图中触发警报。

在我的控制器触发事件中,我有:

$location.path('/');
myService.setAlert("My alert");

我的服务传递"消息"并$broadcast事件

myService.broadcastAlert = function(){
  $rootScope.$broadcast('alertChanged');
};
myService.setAlert = function(message){
  myService.alert = message;
  rootScope.$on('$routeChangeSuccess', function() {
    myService.broadcastAlert();
  });
}

我的另一个视图的控制器收到警报

$scope.$on('alertChanged', function(){
  console.log("New Alert is triggered");
});

这里的问题是rootScope.$on('$routeChangeSuccess')在之后继续运行

也许您需要注销:

myService.setAlert = function(message){
  myService.alert = message;
  var deregister = rootScope.$on('$routeChangeSuccess', function() {
    myService.broadcastAlert();
    deregister();
  });
};