角。js以编程方式将表单字段设置为dirty

时间:2022-12-05 07:58:55

I am programmatically updating some of the fields on my form with a value and I would like to set the field state to $dirty. Doing something like:

我正在用一个值以编程方式更新窗体上的一些字段,我想将字段状态设置为$dirty。做一些像:

$scope.myForm.username.$dirty = true; doesn't seem to work.

scope.myForm.username美元。肮脏的美元= true;似乎没有工作。

There is a method $setPristine that I can use to reset the state of the field but there isn't a $setDirty method?

有一个方法$ setplain我可以用来重置字段的状态,但是没有一个$setDirty方法吗?

So how does one go about doing this?

那么我们该怎么做呢?

I saw this post https://groups.google.com/forum/#!topic/angular/NQKGAFlsln4 but I can't seem to find the $setDirty method. I am using Angular version 1.1.5.

我看到了这篇文章https://groups.google.com/forum/#!topic/角/NQKGAFlsln4但我似乎找不到$setDirty方法。我用的是1。1。5的角度。

11 个解决方案

#1


44  

Since AngularJS 1.3.4 you can use $setDirty() on fields (source). For example, for each field with error and marked required you can do the following:

因为AngularJS 1.3.4可以在字段(源代码)上使用$setDirty()。例如,对于每个有错误和标记的字段,您可以执行以下操作:

angular.forEach($scope.form.$error.required, function(field) {
    field.$setDirty();
});

#2


86  

In your case, $scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue); does the trick - it makes both the form and the field dirty, and appends appropriate CSS classes.

在你的案例中,scope.myForm.username。setViewValue美元(scope.myForm.username。viewValue美元);这个技巧—它使表单和字段都很脏,并添加适当的CSS类。

Just to be honest, I found this solution in new post in the topic from the link from your question. It worked perfectly for me, so I am putting this here as a standalone answer to make it easier to be found.

老实说,我是在你的问题链接中找到这个解决方案的。它非常适合我,所以我把它作为一个独立的答案放在这里,以便更容易被发现。

EDIT:

编辑:

Above solution works best for Angular version up to 1.3.3. Starting with 1.3.4 you should use newly exposed API method $setDirty() from ngModel.NgModelController.

上述解决方案最适用于角版本高达1.3.3。从1.3.4开始,您应该使用来自ngModel.NgModelController的新公开的API方法$setDirty()。

#3


17  

you will have to manually set $dirty to true and $pristine to false for the field. If you want the classes to appear on your input, then you will have to manually add ng-dirty and remove ng-pristine classes from the element. You can use $setDirty() on the form level to do all of this on the form itself, but not the form inputs, form inputs do not currently have $setDirty() as you mentioned.

您将不得不手动将$dirty设置为true,将$ pure设置为false。如果希望类出现在输入中,则必须手动添加ng-dirty并从元素中删除ng-原始类。您可以在窗体级别上使用$setDirty()来在窗体本身上执行所有这些操作,但不是窗体输入,正如您所提到的,窗体输入当前没有$setDirty()。

This answer may change in the future as they should add $setDirty() to inputs, seems logical.

这个答案在未来可能会改变,因为它们应该向输入添加$setDirty(),这似乎是合乎逻辑的。

#4


10  

If you have access to the NgModelController (you can only get access to it from a directive) then you can call

如果您可以访问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);

#5


8  

Made a jsFiddle just for you that solves this issue. simply set $dirty to true, but with a $timeout 0 so it runs after DOM was loaded.

为您制作了一个jsFiddle,用于解决这个问题。只需将$dirty设置为true,但设置$timeout 0,以便在加载DOM之后运行。

Find it here: JsFiddle

在这里找到:JsFiddle

$timeout(function () {
  $scope.form.uName.$dirty = true;
}, 0);

#6


5  

This is what worked for me

这对我起了作用

$scope.form_name.field_name.$setDirty()

#7


5  

You can use $setDirty(); method. See documentation https://docs.angularjs.org/api/ng/type/form.FormController

您可以使用$控件();方法。看到文档https://docs.angularjs.org/api/ng/type/form.FormController

Example:

例子:

$scope.myForm.$setDirty();

#8


4  

A helper function to do the job:

完成这项工作的辅助功能:

function setDirtyForm(form) {
    angular.forEach(form.$error, function(type) {
        angular.forEach(type, function(field) {
            field.$setDirty();
        });
    });
    return form;
}

#9


4  

Angular 2

角2

For anyone looking to do the same in Angular 2 it is very similar apart from getting a hold of the form

对于任何想要在角2中做同样的事情的人来说,除了得到一种形式外,它是非常相似的。

<form role="form" [ngFormModel]="myFormModel" (ngSubmit)="onSubmit()" #myForm="ngForm">
<div class="form-group">
    <label for="name">Name</label>
    <input autofocus type="text" ngControl="usename" #name="ngForm" class="form-control" id="name" placeholder="Name">
    <div [hidden]="name.valid || name.pristine" class="alert alert-danger">
        Name is required
    </div>
</div>
</form>
<button type="submit" class="btn btn-primary" (click)="myForm.ngSubmit.emit()">Add</button>

import { Component, } from '@angular/core';
import { FormBuilder, Validators } from '@angular/common';

@Component({
    selector: 'my-example-form',
    templateUrl: 'app/my-example-form.component.html',
    directives: []
})
export class MyFormComponent {
    myFormModel: any;

    constructor(private _formBuilder: FormBuilder) {
        this.myFormModel = this._formBuilder.group({
            'username': ['', Validators.required],
            'password': ['', Validators.required]
        });
    }

    onSubmit() {
        this.myFormModel.markAsDirty();
        for (let control in this.myFormModel.controls) {
            this.myFormModel.controls[control].markAsDirty();
        };

        if (this.myFormModel.dirty && this.myFormModel.valid) {
            // My submit logic
        }
    }
}

#10


3  

Small additional note to @rmag's answer. If you have empty but required fields that you want to make dirty use this:

@rmag回答的附加说明。如果你有空的但需要的字段,你想让脏的使用这个:

$scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue !== undefined 
    ? $scope.myForm.username.$viewValue : '');

#11


-1  

I'm not sure exactly why you're trying to mark the fields dirty, but I found myself in a similar situation because I wanted validation errors to show up when somebody attempted to submit an invalid form. I ended up using jQuery to remove the .ng-pristine class tags and add .ng-dirty class tags to the appropriate fields. For example:

我不确定您为什么要将字段标记为脏,但是我发现自己处于类似的情况,因为我希望在有人试图提交无效表单时出现验证错误。最后,我使用jQuery删除了.ng原始类标记,并将.ng-dirty类标记添加到适当的字段中。例如:

$scope.submit = function() {
    // `formName` is the value of the `name` attribute on your `form` tag
    if (this.formName.$invalid)
    {
        $('.ng-invalid:not("form")').each(function() {
            $(this).removeClass('ng-pristine').addClass('ng-dirty');
        });
        // the form element itself is index zero, so the first input is typically at index 1
        $('.ng-invalid')[1].focus();
    }
}

#1


44  

Since AngularJS 1.3.4 you can use $setDirty() on fields (source). For example, for each field with error and marked required you can do the following:

因为AngularJS 1.3.4可以在字段(源代码)上使用$setDirty()。例如,对于每个有错误和标记的字段,您可以执行以下操作:

angular.forEach($scope.form.$error.required, function(field) {
    field.$setDirty();
});

#2


86  

In your case, $scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue); does the trick - it makes both the form and the field dirty, and appends appropriate CSS classes.

在你的案例中,scope.myForm.username。setViewValue美元(scope.myForm.username。viewValue美元);这个技巧—它使表单和字段都很脏,并添加适当的CSS类。

Just to be honest, I found this solution in new post in the topic from the link from your question. It worked perfectly for me, so I am putting this here as a standalone answer to make it easier to be found.

老实说,我是在你的问题链接中找到这个解决方案的。它非常适合我,所以我把它作为一个独立的答案放在这里,以便更容易被发现。

EDIT:

编辑:

Above solution works best for Angular version up to 1.3.3. Starting with 1.3.4 you should use newly exposed API method $setDirty() from ngModel.NgModelController.

上述解决方案最适用于角版本高达1.3.3。从1.3.4开始,您应该使用来自ngModel.NgModelController的新公开的API方法$setDirty()。

#3


17  

you will have to manually set $dirty to true and $pristine to false for the field. If you want the classes to appear on your input, then you will have to manually add ng-dirty and remove ng-pristine classes from the element. You can use $setDirty() on the form level to do all of this on the form itself, but not the form inputs, form inputs do not currently have $setDirty() as you mentioned.

您将不得不手动将$dirty设置为true,将$ pure设置为false。如果希望类出现在输入中,则必须手动添加ng-dirty并从元素中删除ng-原始类。您可以在窗体级别上使用$setDirty()来在窗体本身上执行所有这些操作,但不是窗体输入,正如您所提到的,窗体输入当前没有$setDirty()。

This answer may change in the future as they should add $setDirty() to inputs, seems logical.

这个答案在未来可能会改变,因为它们应该向输入添加$setDirty(),这似乎是合乎逻辑的。

#4


10  

If you have access to the NgModelController (you can only get access to it from a directive) then you can call

如果您可以访问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);

#5


8  

Made a jsFiddle just for you that solves this issue. simply set $dirty to true, but with a $timeout 0 so it runs after DOM was loaded.

为您制作了一个jsFiddle,用于解决这个问题。只需将$dirty设置为true,但设置$timeout 0,以便在加载DOM之后运行。

Find it here: JsFiddle

在这里找到:JsFiddle

$timeout(function () {
  $scope.form.uName.$dirty = true;
}, 0);

#6


5  

This is what worked for me

这对我起了作用

$scope.form_name.field_name.$setDirty()

#7


5  

You can use $setDirty(); method. See documentation https://docs.angularjs.org/api/ng/type/form.FormController

您可以使用$控件();方法。看到文档https://docs.angularjs.org/api/ng/type/form.FormController

Example:

例子:

$scope.myForm.$setDirty();

#8


4  

A helper function to do the job:

完成这项工作的辅助功能:

function setDirtyForm(form) {
    angular.forEach(form.$error, function(type) {
        angular.forEach(type, function(field) {
            field.$setDirty();
        });
    });
    return form;
}

#9


4  

Angular 2

角2

For anyone looking to do the same in Angular 2 it is very similar apart from getting a hold of the form

对于任何想要在角2中做同样的事情的人来说,除了得到一种形式外,它是非常相似的。

<form role="form" [ngFormModel]="myFormModel" (ngSubmit)="onSubmit()" #myForm="ngForm">
<div class="form-group">
    <label for="name">Name</label>
    <input autofocus type="text" ngControl="usename" #name="ngForm" class="form-control" id="name" placeholder="Name">
    <div [hidden]="name.valid || name.pristine" class="alert alert-danger">
        Name is required
    </div>
</div>
</form>
<button type="submit" class="btn btn-primary" (click)="myForm.ngSubmit.emit()">Add</button>

import { Component, } from '@angular/core';
import { FormBuilder, Validators } from '@angular/common';

@Component({
    selector: 'my-example-form',
    templateUrl: 'app/my-example-form.component.html',
    directives: []
})
export class MyFormComponent {
    myFormModel: any;

    constructor(private _formBuilder: FormBuilder) {
        this.myFormModel = this._formBuilder.group({
            'username': ['', Validators.required],
            'password': ['', Validators.required]
        });
    }

    onSubmit() {
        this.myFormModel.markAsDirty();
        for (let control in this.myFormModel.controls) {
            this.myFormModel.controls[control].markAsDirty();
        };

        if (this.myFormModel.dirty && this.myFormModel.valid) {
            // My submit logic
        }
    }
}

#10


3  

Small additional note to @rmag's answer. If you have empty but required fields that you want to make dirty use this:

@rmag回答的附加说明。如果你有空的但需要的字段,你想让脏的使用这个:

$scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue !== undefined 
    ? $scope.myForm.username.$viewValue : '');

#11


-1  

I'm not sure exactly why you're trying to mark the fields dirty, but I found myself in a similar situation because I wanted validation errors to show up when somebody attempted to submit an invalid form. I ended up using jQuery to remove the .ng-pristine class tags and add .ng-dirty class tags to the appropriate fields. For example:

我不确定您为什么要将字段标记为脏,但是我发现自己处于类似的情况,因为我希望在有人试图提交无效表单时出现验证错误。最后,我使用jQuery删除了.ng原始类标记,并将.ng-dirty类标记添加到适当的字段中。例如:

$scope.submit = function() {
    // `formName` is the value of the `name` attribute on your `form` tag
    if (this.formName.$invalid)
    {
        $('.ng-invalid:not("form")').each(function() {
            $(this).removeClass('ng-pristine').addClass('ng-dirty');
        });
        // the form element itself is index zero, so the first input is typically at index 1
        $('.ng-invalid')[1].focus();
    }
}