Implementation Details:
I'm currently utilizing ui-router to load a form page in a ui-view div. I found an excellent example by Andres Ekdahi. My question is, how can I perform a $dirty check on multiple forms using the same directive?
Form 1
<form name="myForm" ng-controller="Controller" confirm-on-exit>
Form 2
<form name="iForm" ng-controller="Controller" confirm-on-exit ng-model="myModel">
app.js (directive)
myApp.directive('confirmOnExit', function() {
return {
link: function($scope, elem, attrs) {
// Condition when the back button is pressed
window.onbeforeunload = function(){
if ($scope.myForm.$dirty) {
return "The formI is dirty, do you want to stay on the page?";
}
}
// Conditional statement when a user tries to load another 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();
}
}
});
}
};
});
Error:
Upon initial page load, the $dirty value is false. After filling out the form details and clicking on the third icon (file), I encountered an error regarding the second form's dirty check if ($scope.iForm.$dirty)
, along with an issue relating to $dirty
in the alert.
angular.js:12520 TypeError: Cannot read property '$dirty' of undefined
and
<form name="iForm" ng-controller="Controller" confirm-on-exit="" ng-model="myModel" class="ng-pristine ng-untouched ng-valid ng-scope">
Demo: Plunker