AngularJS- Prompting the user before routing to other controller to save changes -
i have form in controller. if there unsaved change want warn user loosing them when leaving.
first tried:
$scope.$on('$locationchangestart', function (event, next, current) { if ($scope.settingsform.$dirty) { event.preventdefault(); $scope.theuserwantstoleave(function (result) { if (result === "leave") { $location.path($location.url(next).hash()); $scope.$apply(); } }); }
the code above throws error in line $scope.$apply();
:
error: $digest in progress
removing line don't execute redirect.
what right way it?
===
edit:
other option tried handling reacting when need cancel redirection:
$scope.$on('$locationchangestart', function (event, next, current) { if ($scope.settingsform.$dirty) { $scope.theuserwantstoleave(function (result) { if (result === "stay_here") { event.preventdefault(); } }); } });
when doing things way, ui breaking (i see dialog , gone). seems can't call async method while handling event.
i've managed interrupt route change listening $locationchangesuccess
, assigning $route.current
last route.
also, if $scope.theuserwantstoleave
async, callback passed may fire late stop route change. around async call using blocking flag, such oktodiscardchanges
in examples.
js:
$scope.oktodiscardchanges = false; var lastroute = $route.current; $scope.$on('$locationchangesuccess', function () { if ($scope.settingsform.$dirty && !$scope.oktodiscardchanges) { $route.current = lastroute; $scope.errormessage = 'you have unsaved changes. sure want leave?'; } });
html:
<form name="settingsform"> <!-- form stuff --> </form> <div ng-show="errormessage"> {{ errormessage }} <label> <input type="checkbox" ng-model="oktodiscardchanges"> discard changes </label> </div>
hope works!
Comments
Post a Comment