Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Route Controller Not Reloading

I have a very simple AngularJS app that has two routes in it:

#/search
#/results

When I navigate from one route to another everything works as I'd expected. Any resources that are needed are fetched and the content is displayed perfectly.

The problem is when I navigate from one route to the same route (I.e., #/results to #/results) absolutely nothing happens. I understand from the browser's perspective nothing has happened but I'd really like AngularJS to reload the content.

This must be very easy but I'm drawing blanks on this. Can someone please shed some light on this for me?

Thanks,

Jon

like image 438
Jonno Avatar asked Jan 14 '14 23:01

Jonno


1 Answers

When you navigate to the same page, the browser ignores it.
Angular.js has nothing to do with the default behavior of <a href="">.

What you can do, is to create a custom directive which:

  • use $route.reload() to reload the current view (route).
  • use $location.path(newPath) for navigating to other views.

I made an example:

app.directive('xref',function($route, $location){
  return {
    link: function(scope, elm,attr){
      elm.on('click',function(){
        if ( $location.path() === attr.xref ) {
          $route.reload();
        } else {
          scope.$apply(function(){
            $location.path(attr.xref);
          });
        }      
      });
    }
  };
});

In your view just create:

<a xref="/">Home</a>
<a xref="/links">Links</a>
like image 130
Ilan Frumer Avatar answered Oct 20 '22 18:10

Ilan Frumer