我是 angularjs 的新手。当表单有未保存的数据并且用户按下浏览器后退按钮时,有什么方法可以显示警报。任何有关如何实现这一目标的指针将不胜感激。
更新: :
angular.module('myApp.directives', []).directive('confirmOnExit', function() {
return {
link: function($scope, elem, attrs) {
$scope.$on('$locationChangeStart', function(event, next, current) {
if ($scope.myForm.$dirty) {
if(!confirm("Ahh the form is dirty, do u want to continue?")) {
event.preventDefault();
}
}
});
window.onbeforeunload = function(){
alert('me');
if ($scope.myForm.$dirty) {
return "The Form is Dirty.";
}
}
}
};
});
更新代码
angular.module('myApp.directives', []).directive('confirmOnExit', function () {
return {
link: function ($scope, elem, attrs, $rootScope) {
window.onbeforeunload = function () {
if ($scope.myForm.$dirty) {
return " do you want to stay on the page?";
}
}
$rootScope.$watch(function {
return $location.path();
},
function (newValue, oldValue) {
if (newValue != oldvalue) {
// here you can do your tasks
} else {}
},
true);
$scope.$on('$locationChangeStart', function (event, next, current) {
if ($scope.myForm.$dirty) {
if (!confirm("The form is dirty, do you want to stay on the page?")) {
event.preventDefault();
}
}
});
}
};
});