Prevent input from setting form $dirty angularjs

前端 未结 7 1437
天涯浪人
天涯浪人 2021-02-07 05:37

I have an ng form on a page. Inside the form I have several controls which need to display a save dialog when the form is dirty, ie form.$dirty = true. However there are some na

7条回答
  •  一向
    一向 (楼主)
    2021-02-07 06:15

    I used @overthink's solution, but ran into the problem mentioned by @dmitankin. However, I didn't want to attach a handler to the focus event. So instead, I endeavored to override the $pristine property itself and force it to return false always. I ended up using Object.defineProperty which is not supported in IE8 and below. There are workarounds to do this in those legacy browsers, but I didn't need them, so they are not part of my solution below:

    (function () {
        angular
            .module("myapp")
            .directive("noDirtyCheck", noDirtyCheck);
    
        function noDirtyCheck() {
            return {
                restrict: 'A',
                require: 'ngModel',
                link: function (scope, elem, attrs, ctrl) {
                    var alwaysFalse = {
                        get: function () { return false; },
                        set: function () { }
                    };
                    Object.defineProperty(ctrl, '$pristine', alwaysFalse);
                    Object.defineProperty(ctrl, '$dirty', alwaysFalse);
                }
            };
        }
    })();
    

    I am also overriding $dirty so it can't be set as dirty either.

提交回复
热议问题