I have developed a factory that is responsible for detecting state changes and checking if a form has been modified. When the form is dirty, a modal window like a confirmation prompt should appear. However, I am encountering an issue where the $state.go()
method does not seem to work as expected. I am puzzled as to why:
(function() {
var checkStateChangeService = function ($rootScope, $modal) {
var addCheck = function ($scope, form, $state) {
var modalInstanceCtrl = function ($scope, $modalInstance) {
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss("cancel");
};
};
var removeListener = $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if (form.$pristine) {
return;
}
event.preventDefault();
var message = "There are unsaved changes, do you want to continue?";
var title = "Unsaved Changes";
var modalHtml = "<div class=\"panel\">\r\n";
modalHtml += "<h4 class=\"center\" id=\"modalTitle\">" + title + "<\/h4>\r\n";
modalHtml += "<div class=\"small-12 columns\">\r\n";
modalHtml += "<div class=\"modal-body\">" + message + "<\/div>";
modalHtml += "<div class=\"button-box\">\r\n";
modalHtml += "<button ng-click='ok()' class=\"tiny\">OK<\/button>\r\n";
modalHtml += "<button ng-click='cancel()' class=\"tiny\">Cancel<\/button>\r\n";
modalHtml += "<\/div>\r\n";
modalHtml += "<\/div>\r\n";
modalHtml += "<\/div>";
var modalInstance = $modal.open({
template: modalHtml,
controller: modalInstanceCtrl
});
modalInstance.result.then(function () {
$state.go(toState);
}, function () {
$state.go(fromState);
});
});
$scope.$on("$destroy", removeListener);
};
return { checkFormOnStateChange: addCheck};
}
var module = angular.module("traApp");
module.service("checkStateChangeService", checkStateChangeService);
}());
Despite no visible errors, I am unable to understand why this functionality is not working properly. Similar implementations have been successful in other examples.