如何对AngularJS中加载相同URL的链接做出反应?

问题描述 投票:0回答:1

我在页面上有一个表单,使用普通的锚标记从我的菜单链接。

现在如果我已经在该页面上再次单击该菜单项,我想检查未保存的更改并显示模式以询问您是否确实要重新加载,如果有未保存的更改,或者只是重置页面,如果没有。

我如何在AngularJS中做到这一点?我希望将菜单项保持为普通锚标记。

angularjs angularjs-routing
1个回答
0
投票

解决方案取决于您是否计划在应用程序的其他位置重用此功能,或将其限制为仅此单一形式。

如果您打算在整个应用程序中重复使用此功能,并在用户尝试转到已经打开的链接(从菜单)时执行检查,您可以随时将网址与当前网址进行比较。这段代码并不完美,但它可以解决这个问题,将目标网址与当前网址进行比较。

//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>

如果你想将这个功能限制在这个窗体的控制器上,我建议你查看这篇文章,了解如何解决这个问题:Showing alert in angularjs when user leaves a page

© www.soinside.com 2019 - 2024. All rights reserved.