Detect unsaved data using angularjs

后端 未结 4 1564
我寻月下人不归
我寻月下人不归 2020-12-07 17:39

I\'m a newbie to AngularJs, so this might be trivial. Are there any inbuilt AngularJs directive to detect unsaved data in a form. If not then how to go about wr

4条回答
  •  爱一瞬间的悲伤
    2020-12-07 18:11

    This is what I did in my Controller.

    When I get the form data for modification, first I save its string representation to a scope variable like this:

    $scope.originalData = JSON.stringify($scope.data);
    

    Then I create a state change listener:

     var $locationChangeStartUnbind = $scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if ($scope.originalData !== JSON.stringify($scope.data)) {
            //Show alert and prevent state change
        } else {
            //DO NOTHING THERE IS NO CHANGES IN THE FORM
        }
    });
    

    Then I clear the listener on scope destroy:

    $scope.$on('$destroy', function () {
        window.onbeforeunload = null;
        $locationChangeStartUnbind();
    });
    

    Hope this helps.

提交回复
热议问题