1

I have a strange problem with calling the e.preventDefault inside handler for a $locationChangeStart event. I have something like this:

var unregisterCallback = _this.$rootScope.$on('$locationChangeStart', function (e) {
    e.preventDefault();
});

This is happens in a link function for one of the directivies. The problem is that when I click an anchor element with some path, it actually navigates to it and then back. I'm using component router from Angular 1.5. This pretty much makes this usless, as I'm trying to show a confirmation dialog before user nagivates away without saving changes. The thing is, due to this re-navigation he looses all changes anyways. Any idea what's going on?

sdgluck
  • 24,894
  • 8
  • 75
  • 90
macwier
  • 1,063
  • 1
  • 6
  • 19

1 Answers1

0

In the code you are trying to prevent the default event in the $locationChangeStart, but you don't want to navigate to a new page on click of a anchor() tag. In that case you can remove the href ="#" in the anchor tag and follow the below method

Link

Another method to prevent the default action for all the anchor tags you can have directive to do so

 app.directive('a', function() {
    return {
        restrict: 'E', // restricts to html elment
        link: function(scope, elm, attrs) {
            if(attrs.ngClick || attrs.href === '' || attrs.href === '#'){
                elm.on('click', function(ev){
                    ev.preventDefault(); // prevents the default functionality of the tag
                });
            }
        }
   };
});
Aswin
  • 43
  • 2
  • 3
  • Your 'link' isn't a link (just a text). Also, the anchor has a ng-href attribute which specifies the path to navigate to. – macwier Jul 07 '16 at 12:27