Detect unsaved changes and alert user using angularjs

前端 未结 7 1673
执念已碎
执念已碎 2020-11-29 18:50

Below is the code so far

    


    

        
7条回答
  •  庸人自扰
    2020-11-29 19:40

    I've extended the @Anders answer to clean up listeners (unbind listers) when directive is destroyed (ex: when route changes), and added some syntactic sugar to generalise the usage.

    confirmOnExit Directive:

    /**
     * @name confirmOnExit
     * 
     * @description
     * Prompts user while he navigating away from the current route (or, as long as this directive 
     * is not destroyed) if any unsaved form changes present.
     * 
     * @element Attribute
     * @scope
     * @param confirmOnExit Scope function which will be called on window refresh/close or AngularS $route change to
     *                          decide whether to display the prompt or not.
     * @param confirmMessageWindow Custom message to display before browser refresh or closed.
     * @param confirmMessageRoute Custom message to display before navigating to other route.
     * @param confirmMessage Custom message to display when above specific message is not set.
     * 
     * @example
     * Usage:
     * Example Controller: (using controllerAs syntax in this example)
     * 
     *      angular.module('AppModule', []).controller('pageCtrl', [function () {
     *          this.isDirty = function () {
     *              // do your logic and return 'true' to display the prompt, or 'false' otherwise.
     *              return true;
     *          };
     *      }]);
     * 
     * Template:
     * 
     *      
    * * @see * http://stackoverflow.com/a/28905954/340290 * * @author Manikanta G */ ngxDirectivesModule.directive('confirmOnExit', function() { return { scope: { confirmOnExit: '&', confirmMessageWindow: '@', confirmMessageRoute: '@', confirmMessage: '@' }, link: function($scope, elem, attrs) { window.onbeforeunload = function(){ if ($scope.confirmOnExit()) { return $scope.confirmMessageWindow || $scope.confirmMessage; } } var $locationChangeStartUnbind = $scope.$on('$locationChangeStart', function(event, next, current) { if ($scope.confirmOnExit()) { if(! confirm($scope.confirmMessageRoute || $scope.confirmMessage)) { event.preventDefault(); } } }); $scope.$on('$destroy', function() { window.onbeforeunload = null; $locationChangeStartUnbind(); }); } }; });

    Usage: Example Controller: (using controllerAs syntax in this example)

    angular.module('AppModule', []).controller('pageCtrl', [function () {
        this.isDirty = function () {
            // do your logic and return 'true' to display the prompt, or 'false' otherwise.
    
            return true;
        };
    }]);
    

    Template:

提交回复
热议问题