实施细则:
我正在使用ui-router在ui-view div中加载表单页面。我在Andres Ekdahi中提到了很好的例子,我如何使用同一指令对多个表单进行$脏检查?
Form1中
<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
答案 0 :(得分:2)
有一种更简单的方法。
只需要将您的指令放在表单元素上,然后通过链接函数访问表单控制器:
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();
}
}
});
}
};
});
答案 1 :(得分:1)
在检查表单是否脏之前检查表单是否存在。做点什么
if ($scope.myForm && $scope.myForm.$dirty) {
if(!confirm("myForm. Do you want to continue ?")) {
event.preventDefault();
}
}
if ($scope.iForm && $scope.iForm.$dirty) {
if(!confirm("iform. Do you want to continue ?")) {
event.preventDefault();
}
}
答案 2 :(得分:1)
从name
的{{1}}属性中获取指令会使指令更简单,因此只有一个条件位于指令&amp;它可以在很多地方重复使用。
form
<强>代码强>
<form name="myForm" ng-controller="Controller" confirm-on-exit>