0

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Dominik G
  • 1,459
  • 3
  • 17
  • 37
  • You can create a temporary variables where you can store the original values of the input text or whatever is modified in the UI. Check the temp variables data and the modified data on click of the anchor tag. If the value is different then show the pop up otherwise reload it. – Bijay Koirala Apr 25 '19 at 08:51
  • Thanks. The problem is not, how to check if changes occurred, but how to get an event if I'm on "#/MyEditor" and the link to "#/MyEditor" (same url) is clicked. – Dominik G Apr 25 '19 at 12:54

1 Answers1

0

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

rze
  • 248
  • 1
  • 3
  • 14