angularjs - 如何检查数据模型值改变角度?

angularjs - 如何检查数据模型值改变角度?,第1张

我有一个使用angular.js的在线Web表单。当用户编辑信息并单击它时,它会丢失未保存的数据。如何检查数据模型值是否已更改,并在导航之前警告用户他们有未保存的信息需要保存?

我已经分享了这个例子:plunker

  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.master = {};

      $scope.update = function(user) {
        $scope.master = angular.copy(user);
      };

      $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
      };

      $scope.reset();
    }]);

最佳答案:

1 个答案:

答案 0 :(得分:0)

当用户离开页面注入此指令并更改消息时,我已使用此指令警告未保存的数据

<html ng-app="myApp">
<head>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    function Ctrl($scope) {
        var initial = {text: 'initial value'};
        $scope.mySample = angular.copy(initial);
    }

    angular.module("myApp", []).directive('confirmOnExit', function() {
        return {
            link: function($scope, elem, attrs) {
                window.onbeforeunload = function(){
                    if ($scope.myForm.$dirty) {
                        return "The form is dirty, do you want to stay on the page?";
                    }
                }
                $scope.$on('$locationChangeStart', function(event, next, current) {
                    if ($scope.myForm.$dirty) {
                        if(!confirm("The form is dirty, do you want to stay on the page?")) {
                            event.preventDefault();
                        }
                    }
                });
            }
        };
    });
    </script>
</head>
<body>
    <form name="myForm" ng-controller="Ctrl" confirm-on-exit>
      Text: <input name="input" ng-model="mySample.text">
        <p>mySample = {{mySample.text}}</p>
    </form>
</body>
</html>
本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复