2

I want to trigger an alert in another view after $location.path() has changed the ng-view (without using $rootScope).

In my controller trigger event I have :

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

My service passes the "message" and $broadcast an event

myService.broadcastAlert = function(){
  $rootScope.$broadcast('alertChanged');
};

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

My other view's controller receives an alert

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

The problem here is the rootScope.$on('$routeChangeSuccess') continues to run after

4

1 回答 1

2

也许您需要注销:

myService.setAlert = function(message){
  myService.alert = message;
  var deregister = rootScope.$on('$routeChangeSuccess', function() {
    myService.broadcastAlert();
    deregister();
  });
};
于 2013-11-14T10:42:38.733 回答