我的页面上有一个表单,该表单是使用普通锚标签从菜单链接的。
现在,如果我已经在该页面上时再次单击该菜单项,那么我想检查是否有未保存的更改,或者显示一个模式以询问您是否真的要重新加载,是否有未保存的更改,或者只是重置页面,如果没有的话。
我将如何在AngularJS中执行此操作? 最好让菜单项保持普通锚标签。
答案 0 :(得分:0)
解决方案取决于您是打算在应用程序的其他位置重用此功能,还是将其限制为仅此一种形式。
如果您打算在整个应用程序中重用此代码,并在用户尝试访问其已经存在的链接(从菜单)时进行检查,则始终可以将URL与当前URL进行比较。这段代码不是完美的,但它能使您理解,将目标URL与当前URL进行比较。
即
//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