Sut*_*bey 6 javascript forms angularjs
如果用户尝试保留未保存的已编辑表单,则会弹出一个消息框
"此页面要求您确认是否要离开 - 您输入的数据可能无法保存.请保留页面并保持在页面上"
我们可以通过浏览器的一些特殊功能来调用此确认框吗?我想在AngularJS应用程序中实现它
Ben*_*esh 11
术士的答案部分正确,但这样做会破坏可测试性.
在Angular中,您需要使用$ window,并且您需要$dirty
在表单上观看.您需要有一个命名表格,请注意name="myForm"
以下内容.然后你可以$watch
$dirty
在你的表格中$scope
:
app.controller('MainCtrl', function($scope, $window) {
$scope.name = 'World';
var win = $window;
$scope.$watch('myForm.$dirty', function(value) {
if(value) {
win.onbeforeunload = function(){
return 'Your message here';
};
}
});
});
Run Code Online (Sandbox Code Playgroud)
HTML
<form name="myForm">
Name: <input type="text" ng-model="name"/>
</form>
Run Code Online (Sandbox Code Playgroud)
这是一个演示的插图:http://plnkr.co/edit/3NHpU1
您可以使用"onbeforeunload"事件.语法如下:
window.onbeforeunload = function () {
return "Your text string you want displayed in the box";
}
Run Code Online (Sandbox Code Playgroud)
此事件将弹出您在上面描述的确认对话框,询问用户是否真的要离开页面.
希望这可以帮助.
小智 5
如果要在确定表单脏时取消路由更改,可以执行以下操作:
$rootScope.$on('$locationChangeStart', function(event) {
event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
这将取消路由并让您保持当前页面.
归档时间: |
|
查看次数: |
9362 次 |
最近记录: |