Angularjs 如何检查更改的数据模型值?
我有一个使用angular.js的在线Web表单。当用户编辑信息并单击“上一步”时,将丢失未保存的数据。如何检查数据模型值是否已更改,并在导航离开之前警告用户有未保存的信息需要保存 我举了一个例子:Angularjs 如何检查更改的数据模型值?,angularjs,Angularjs,我有一个使用angular.js的在线Web表单。当用户编辑信息并单击“上一步”时,将丢失未保存的数据。如何检查数据模型值是否已更改,并在导航离开之前警告用户有未保存的信息需要保存 我举了一个例子: 我使用此指令在用户离开页面时警告未保存的数据,并插入此指令并更改消息 <html ng-app="myApp"> <head> <script src="http://code.angularjs.org/1.1.2/angular.min.js"><
我使用此指令在用户离开页面时警告未保存的数据,并插入此指令并更改消息
<html ng-app="myApp">
<head>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
function Ctrl($scope) {
var initial = {text: 'initial value'};
$scope.mySample = angular.copy(initial);
}
angular.module("myApp", []).directive('confirmOnExit', function() {
return {
link: function($scope, elem, attrs) {
window.onbeforeunload = function(){
if ($scope.myForm.$dirty) {
return "The form is dirty, do you want to stay on the page?";
}
}
$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();
}
}
});
}
};
});
</script>
</head>
<body>
<form name="myForm" ng-controller="Ctrl" confirm-on-exit>
Text: <input name="input" ng-model="mySample.text">
<p>mySample = {{mySample.text}}</p>
</form>
</body>
</html>
函数Ctrl($scope){
var initial={text:'initial value'};
$scope.mySample=angular.copy(首字母);
}
angular.module(“myApp”,[]).directive('confirmOnExit',function(){
返回{
链接:函数($scope、elem、attrs){
window.onbeforeunload=函数(){
如果($scope.myForm.$dirty){
return“表单已脏,是否要保留在页面上?”;
}
}
$scope.$on(“$locationChangeStart”,函数(事件、下一个、当前){
如果($scope.myForm.$dirty){
如果(!confirm(“表单脏了,是否要留在页面上?”){
event.preventDefault();
}
}
});
}
};
});
正文:
mySample={{mySample.text}
您尝试过代码吗?是的,我使用了验证,但没有enough@user3277743为什么验证还不够?我将创建示例plunker等待?编辑并发布整个代码。我的plunker不起作用。请使用此代码并检查。它会起作用的
<html ng-app="myApp">
<head>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
function Ctrl($scope) {
var initial = {text: 'initial value'};
$scope.mySample = angular.copy(initial);
}
angular.module("myApp", []).directive('confirmOnExit', function() {
return {
link: function($scope, elem, attrs) {
window.onbeforeunload = function(){
if ($scope.myForm.$dirty) {
return "The form is dirty, do you want to stay on the page?";
}
}
$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();
}
}
});
}
};
});
</script>
</head>
<body>
<form name="myForm" ng-controller="Ctrl" confirm-on-exit>
Text: <input name="input" ng-model="mySample.text">
<p>mySample = {{mySample.text}}</p>
</form>
</body>
</html>