防止输入设置$ dirty angularjs

aca*_*cia 17 angularjs

我在页面上有一个表格.在表单内部,我有几个控件,当表单很脏时需要显示一个保存对话框,即表单.$ dirty = true.但是,我不希望弄脏表单的形式有一些导航控件.假设我无法将控件移出表单.

请参阅:http://plnkr.co/edit/bfig4B

如何使表单中的选择框不脏?

ove*_*ink 25

这是使用指令而不使用$ timeout的@ acacia的答案版本.这将使您的控制器更清洁.

.directive('noDirtyCheck', function() {
  // Interacting with input elements having this directive won't cause the
  // form to be marked dirty.
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$pristine = false;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

然后在你的表单中使用它:

<input type="text" name="foo" ng-model="x.foo" no-dirty-check>
Run Code Online (Sandbox Code Playgroud)


Kas*_*man 13

我使用了@ overthink的解决方案,但遇到了@dmitankin提到的问题.但是,我不想将处理程序附加到焦点事件.所以相反,我努力覆盖$ pristine属性本身并强制它始终返回false.我最终使用了IE8及以下版本不支持的Object.defineProperty.有些解决方法可以在这些旧版浏览器中执行此操作,但我不需要它们,因此它们不属于我的解决方案:

(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);
            }
        };
    }
})();
Run Code Online (Sandbox Code Playgroud)

我也凌驾于$脏,所以它也不能被设置为脏.


Del*_*kin 12

将$ pristine属性设置为false,仅在初始化时才有效,直到在窗体上调用$ setPristine()为止.然后你的控件让它的$ pristine回到true,改变输入的值会使你的表单变脏.为避免这种情况,请将$ pristine设置为焦点:

link: function(scope, elm, attrs, ctrl) {
    elm.focus(function () {
        ctrl.$pristine = false;
    });
}
Run Code Online (Sandbox Code Playgroud)


aca*_*cia 7

如果控件是原始的,Angular仅将表单设置为脏.所以这里的诀窍是将控件上的$ pristine设置为false.您可以在控制器中超时执行此操作.

请参阅:http://plnkr.co/edit/by3qTM