Prevent input from setting form $dirty angularjs

前端 未结 7 1448
天涯浪人
天涯浪人 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:09

    I ran into some problems with that implementation, so here is mine (more complex):

    app.directive('noDirtyCheck', [function () {
            // Interacting with input elements having this directive won't cause the
            // form to be marked dirty.
            // http://stackoverflow.com/questions/17089090/prevent-input-from-setting-form-dirty-angularjs
            return {
                restrict: 'A',           
                require: ['^form', '^ngModel'],
    
                link: function (scope, element, attrs, controllers) {
                    var form = controllers[0];
                    
                    var currentControl = controllers[1];
    
                    var formDirtyState = false;
    
                    var manualFocus = false;
    
                    element.bind('focus',function () {
                        manualFocus = true;
                        if (form) {                        
                            window.console && console.log('Saving current form ' + form.$name + ' dirty status: ' + form.$dirty);
                            formDirtyState = form.$dirty; // save form's dirty state
                        }
                     });
                    
                    element.bind('blur', function () {
                        if (currentControl) {
                            window.console && console.log('Resetting current control (' + currentControl.$name + ') dirty status to false (called from blur)');
                            currentControl.$dirty = false; // Remove dirty state but keep the value
                            if (!formDirtyState && form && manualFocus) {
                                window.console && console.log('Resetting ' + form.$name + ' form pristine state...');
                                form.$setPristine();
                            }
                            manualFocus = false;
                            //          scope.$apply();
                        }
                    });
                }
            };
        }]);

提交回复
热议问题