Angular.js以编程方式将表单字段设置为脏

sup*_*er9 105 angularjs

我以编程方式更新我的表单上的一些字段与值,我想将字段状态设置为$dirty.做类似的事情:

$scope.myForm.username.$dirty = true; 似乎不起作用.

有一种方法$setPristine可以用来重置字段的状态但是没有$setDirty方法吗?

那么如何去做呢?

我看到这篇文章https://groups.google.com/forum/#!topic/angular/NQKGAFlsln4但我似乎无法找到该$setDirty方法.我使用的是Angular 1.1.5版.

rma*_*mag 86

在你的情况下,$scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue);诀窍 - 它使表单和字段都变脏,并附加适当的CSS类.

说实话,我从你问题的链接中找到了主题中新帖子的解决方案.它对我来说非常合适,所以我把它放在这里作为一个独立的答案,以便更容易找到.

编辑:

以上解决方案最适用于1.3.3的Angular版本.与1.3.4开始,你应该使用新暴露的API方法$setDirty()ngModel.NgModelController.

  • 感谢您的注意,您节省了我的一天"高达1.3.3.从1.3.4开始,您应该使用新暴露的API方法" (4认同)

Mat*_*ski 51

从AngularJS 1.3.4开始,您可以$setDirty()在字段()上使用.例如,对于每个有错误且标记为必需的字段,您可以执行以下操作:

angular.forEach($scope.form.$error.required, function(field) {
    field.$setDirty();
});
Run Code Online (Sandbox Code Playgroud)


The*_*One 17

你将不得不手动设置$dirtytrue$pristinefalse田间.如果希望类出现在输入中,则必须手动添加ng-dirty和删除ng-pristine元素中的类.您可以$setDirty()在表单级别上使用表单本身上的所有这些,但不是表单输入,表单输入当前没有$setDirty()您提到的.

这个答案可能在将来发生变化,因为它们应该增加$setDirty()输入,似乎是合乎逻辑的.

  • $ setPristine()在输入字段级别但在1.2.26中仍然没有$ setDirty :-( (3认同)

Mar*_*kka 10

如果您有权访问NgModelController(您只能从指令访问它),那么您可以调用

ngModel.$setViewValue("your new view value");
// or to keep the view value the same and just change it to dirty
ngModel.$setViewValue(ngModel.$viewValue);
Run Code Online (Sandbox Code Playgroud)


Gil*_*leg 9

为你解决这个问题的jsFiddle.只需将$ dirty设置为true,但是$timeout 0在加载DOM之后运行它就会运行.

在这里找到它:JsFiddle

$timeout(function () {
  $scope.form.uName.$dirty = true;
}, 0);
Run Code Online (Sandbox Code Playgroud)


sha*_*how 6

这对我有用

$scope.form_name.field_name.$setDirty()
Run Code Online (Sandbox Code Playgroud)


小智 6

你可以使用$setDirty();方法.请参阅文档https://docs.angularjs.org/api/ng/type/form.FormController

例:

$scope.myForm.$setDirty();
Run Code Online (Sandbox Code Playgroud)


Rod*_*ira 5

帮助函数完成工作:

function setDirtyForm(form) {
    angular.forEach(form.$error, function(type) {
        angular.forEach(type, function(field) {
            field.$setDirty();
        });
    });
    return form;
}
Run Code Online (Sandbox Code Playgroud)