5

I've tried doing the following in my controller:

  $scope.$on("$routeChangeStart", function (event, next, current) {
       if (!confirm('are you sure ?')) {
         event.preventDefault();           
       }
  });

But it doesn't work. Is that not supposed to be the way to do it ?

Sam
  • 13,934
  • 26
  • 108
  • 194
  • Where are you doing this? Can you post a jsfiddle? You probably want to do this on the $rootScope. I'd suggest putting it in where your app bootstrap's itself. Post a jsFiddle and I'll try to fix it for you. – Chris Nicola Oct 14 '13 at 17:58
  • nice of you, but I ended up using ui-router so I had to use $stateChangeStart instead, which just works. – Sam Oct 14 '13 at 18:31

2 Answers2

0

I would put a directive on your links, that should be confirmed before changing the route. I just prototyped it in JSFiddle, I did not test it. But I think, this should be the proper way.

(function (angular) {
  module = angular.module('confirm', []);
  ConfirmDirective = function () {
      return {
        restrict: 'A',
        link: function (scope, elm, attrs, ctrls) {
            angular.element(elm).bind('click', function (event) {
                alert("Sure?");
                event.preventDefault();
                return false; //or true, depends on you
            });
        }
    };
  };
  module.directive("confirm", ConfirmDirective);
}(angular));

http://jsfiddle.net/L6xBF/3/

Check and try it.

Regards

kfis
  • 4,739
  • 22
  • 19
  • 1
    That's nice but it's not what I'm looking for. I need to watch for route change. That includes when the user hits the back button of the browser. – Sam Apr 25 '13 at 11:45
  • You may also want to capture all route changes, and adding a confirmation to every single link just doesn't look like the best way to do it. – andersonvom May 29 '13 at 17:39
0

I ended up using ui-router, so the way I'm doing it is:

$scope.$on('$stateChangeStart', function (event) {
     if (!confirm('are you sure ?')) {
         event.preventDefault();
     }
});

and it works.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Sam
  • 13,934
  • 26
  • 108
  • 194