How to react to a link loading the same URL in AngularJS?

66 Views Asked by At

I have a form on a page that is linked from my menu using a normal anchor tag.

Now if that menu item is clicked again when I'm already on that page, I want to check for unsaved changes and either show a modal to ask if you really want to reload, if there are unsaved changes, or just reset the page, if there are none.

How would I go to do this in AngularJS? Preferably I would like to keep the menu item a normal anchor tag.

1

There are 1 best solutions below

0
rze On

The solution depends on whether you plan to reuse this functionality elsewhere in your app or limit it to just this single form.

If you plan to reuse this throughout your application and perform a check anytime a user attempts to go to a link(from the menu) on which they're already on, you could always compare the url to the current url. This code isn't perfect but it gets the idea across, perform a comparison of the target url with the current.

i.e.

//not sure if you're using a router or hardcoded the links, however I'd recommend an approach that isn't hard coded links. This array just mimics the definitions of routes.
$scope.urlDictionary = [
{label:"Page 1", url: "/page1"},
{label:"Page 2", url: "/page2"},
]


$scope.goToURL = function(url){
  //check if the current url is equal to the url of which they want to navigate to
  if($location.url == url){
    //prompt modal to check if they actually want to navigate away
    //if(yes) $location.url = url;
    //else return;
  }
  //go to the url if it isnt equal to the current url
  else{
    $location.url = url;
  }
}
<!-- menu, just used ul to get the idea across-->
<ul>
  <li ng-repeat="u in urlDictionary" ng-click="goToURL(u.url)">{{u.label}}</li>
</ul>

if you want to limit this functionality to just this form's controller, I'd recommend checking out this post for an idea of how to go about it: Showing alert in angularjs when user leaves a page