Monday, June 1, 2015

AngularJS: How to stop a user from leaving a dirty form?

A colleague asked our dev group how an AngularJS app could be configured prompt a user before leaving an unsaved form.

One suggested approach was to use the run block and watch the $stateChangeStart event. The only problem with this is that the form is really only visible from the view and controller in which its defined.

I suggested writing a directive that could be added to the form element. This is what it looks like:

app.directive('formExitPrompt', function ($rootScope, $modal) {
  return {
    require: 'form',
    restrict: 'A',
    link: function (scope, el, attrs, formCtrl) {
      $rootScope.$on('$stateChangeStart', promptUser);
      function promptUser () {
        if (formCtrl.$dirty) {
          var modalInstance = ${
             * Modal configuration goes here! 

Here's a plunker with formExitPrompt in action.