Angularjs: preventing route changes

I tried to do the following in my controller:

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

But that will not work. Shouldn't that be the way to do it?

+5
source share
2 answers

I ended up using ui-router, so I do this:

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

and it works.

0
source

I would put a directive on your links, which must be confirmed before changing the route. I just prototyped it in JSFiddle, I did not test it. But I think this should be the right 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.

Hi

0
source

All Articles