1

I'm using the following directive:

app.directive("ngOutside", function($document, $rootScope){
  return {
    restrict: "A",
    link: function(scope, elem, attr, ctrl){

      elem.bind("click", function(e){
        e.stopPropagation();
      });

      $document.bind("click", function(){
        $rootScope.$apply(function(){
          $rootScope.nav = false;
          $rootScope.aside.on = false;
        });
      });

    }
  }
});

Now I apply this in my HTML like so:

<nav ng-outside>
  <ul>
    <li><a href="/home">Home</a></li>
    <li><a href="/dashboard">Dashboard</a></li>
  </ul>
</nav>

Originally I was using hashbang mode and the directive worked fine. Now I am using HTML5 mode and the e.stopPropagation is stopping Angular working out the routing when one of the nav links is clicked. Instead, the browser now treats the link normally and does a full page reload to the location.

If I remove the following, it solves the problem but the directive no longer does it's job:

elem.bind("click", function(e){
  e.stopPropagation();
});

How can I implement the 'click anywhere but here' type directive without breaking links in HTML5 mode?

CaribouCode
  • 13,998
  • 28
  • 102
  • 174
  • Have you specified a base href in your index file? `````` – Duncan Mar 09 '15 at 15:42
  • @Duncan Yeh that's in there. I don't think the issue is with using the `HTML5mode` because when I remove the `e.stopPropagation` part of that directive, route changes work perfectly. – CaribouCode Mar 09 '15 at 15:48
  • Does `e.preventDefault()` not achieve the desired effect? – Michelangelo Mar 09 '15 at 15:50
  • @Mikey no the e.stopPropagation is used to stop the directive firing when clicking on the directive element. The idea was taken from here: http://stackoverflow.com/questions/12931369/click-everywhere-but-here-event – CaribouCode Mar 09 '15 at 15:52
  • So just to understand the use case here, for I am wracking my brain trying to understand, you are telling angular to not allow a user to click on the nav, but you still want the links in the nav element to accept clicks? – acg Mar 09 '15 at 17:46
  • @acg no the concept is, when the user clicks on any element except within the nav, a function fires. – CaribouCode Mar 10 '15 at 14:04
  • Thanks, I know you may not like this answer and you probably already did it and were hoping for clarity on this, but I think you may need to move the ngOutside to a div that contains all the other content. – acg Mar 10 '15 at 14:50
  • @acg Yeh that's the current workaround I've done. – CaribouCode Mar 10 '15 at 15:09

0 Answers0