实现细节:
我正在使用 ui-router 在 ui-view div 中加载表单页面。我通过 Andres Ekdahi 提到了很好的例子, 如何使用相同的指令对多个表单进行 $dirty 检查?
表单 1
<form name="myForm" ng-controller="Controller" confirm-on-exit>
表格2
<form name="iForm" ng-controller="Controller" confirm-on-exit ng-model="myModel">
app.js(指令)
myApp.directive('confirmOnExit', function() {
return {
link: function($scope, elem, attrs) {
// condition when back page is pressed
window.onbeforeunload = function(){
if ($scope.myForm.$dirty) {
return "The formI is dirty, do you want to stay on the page?";
}
}
// condition when user try to load other form (via icons )
$scope.$on('$stateChangeStart', function(event, next, current) {
if ($scope.myForm.$dirty) {
if(!confirm("myForm. Do you want to continue ?")) {
event.preventDefault();
}
}
if ($scope.iForm.$dirty) {
if(!confirm("iform. Do you want to continue ?")) {
event.preventDefault();
}
}
});
}
};
});
错误:
第一次加载页面时,$dirty 值为 false。然后我填写表单详细信息并单击第三个图标(文件),我得到第二个表单脏检查错误 if ($scope.iForm.$dirty)
和 $dirty
处于警戒状态。
angular.js:12520 TypeError: Cannot read property '$dirty' of undefined
和
<form name="iForm" ng-controller="Controller" confirm-on-exit="" ng-model="myModel" class="ng-pristine ng-untouched ng-valid ng-scope">
演示:Plunker
最佳答案
有一个更简单的方法。
只需将指令放在表单元素上并通过链接函数访问表单 Controller 即可:
myApp.directive('confirmOnExit', function() {
return {
require: 'form',
link: function($scope, elem, attrs, formController) {
// condition when back page is pressed
window.onbeforeunload = function(){
if (formController.$dirty) {
return "The form '" + formController.$name + "' is dirty, do you want to stay on the page?";
}
}
// condition when user try to load other form (via icons )
$scope.$on('$stateChangeStart', function(event, next, current) {
if (formController.$dirty) {
if(!confirm(formController.$name + ". Do you want to continue ?")) {
event.preventDefault();
}
}
});
}
};
});
关于javascript - 检查 angularjs 中未保存的表单数据(使用 ui-router 的多个表单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36271858/