Angular.js가 프로그래밍 방식으로 양식 필드를 더티로 설정합니다.
폼의 일부 필드를 값으로 프로그래밍 방식으로 업데이트하고 있으며 필드 상태를 다음과 같이 설정하려고 합니다.$dirty
. 다음과 같은 작업을 수행합니다.
$scope.myForm.username.$dirty = true;
효과가 없는 것 같습니다.
방법이 있다$setPristine
필드 상태를 리셋하기 위해 사용할 수 있지만 필드 상태 리셋에는$setDirty
방법?
그럼 어떻게 해야 할까요?
https://groups.google.com/forum/#!topic/angular/NQKGAFln4라는 게시물을 봤는데 찾을 수 없습니다.$setDirty
방법.Angular 버전 1.1.5를 사용하고 있습니다.
당신의 경우,$scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue);
does the trick - 폼과 필드를 모두 더럽히고 적절한 CSS 클래스를 추가합니다.
솔직히 말하면, 질문의 링크에서 토픽의 새로운 투고에서 이 솔루션을 찾았습니다.저에게 딱 맞아떨어졌기 때문에 찾기 쉽도록 단독 답변으로 이 자리에 올려놓았습니다.
편집:
위의 솔루션은 최대 1.3.3의 Angular 버전에 가장 적합합니다.1.3.4부터는 새롭게 노출된 API 방식을 사용해야 합니다.$setDirty()
부터ngModel.NgModelController
.
AngularJS 1.3.4를 사용할 수 있습니다.$setDirty()
필드(소스)에 있습니다.예를 들어 오류가 발생하여 필수 필드로 표시된 각 필드에 대해 다음을 수행할 수 있습니다.
angular.forEach($scope.form.$error.required, function(field) {
field.$setDirty();
});
수동으로 설정할 필요가 있습니다.$dirty
로.true
그리고.$pristine
로.false
필드용입니다.입력에 클래스를 표시하려면 , 수동으로 추가할 필요가 있습니다.ng-dirty
제거하다ng-pristine
클래스입니다.사용할 수 있습니다.$setDirty()
양식 입력이 아닌 양식 자체에서 이 모든 것을 하기 위한 양식 수준에서 양식 입력은 현재 가지고 있지 않습니다.$setDirty()
말씀하신대로.
이 답변은 나중에 변경될 수 있습니다.$setDirty()
논리적으로 보입니다.
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);
당신을 위해 이 문제를 해결하는 jsFiddle을 만들었습니다.단순히 $140를 true로 설정해 두지만$timeout 0
DOM이 로드된 후에 실행됩니다.
검색: JsFiddle
$timeout(function () {
$scope.form.uName.$dirty = true;
}, 0);
이것이 나에게 효과가 있었다.
$scope.form_name.field_name.$setDirty()
사용할 수 있습니다.$setDirty();
방법.매뉴얼 https://docs.angularjs.org/api/ng/type/form.FormController 를 참조해 주세요.
예:
$scope.myForm.$setDirty();
작업을 수행하기 위한 도우미 기능:
function setDirtyForm(form) {
angular.forEach(form.$error, function(type) {
angular.forEach(type, function(field) {
field.$setDirty();
});
});
return form;
}
각도 2
Angular 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
}
}
}
@rmag 답변에 대한 작은 추가 메모.더티하게 할 빈 필수 필드가 있는 경우 다음을 수행합니다.
$scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue !== undefined
? $scope.myForm.username.$viewValue : '');
왜 필드를 더럽게 표시하려고 하는지 정확히 알 수 없지만, 누군가가 잘못된 양식을 제출하려고 할 때 검증 오류가 나타나기를 원했기 때문에 저도 비슷한 상황에 처해 있었습니다.하여 jQuery를 했습니다..ng-pristine
및 add " " " " " 를 추가합니다..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();
}
}
언급URL : https://stackoverflow.com/questions/18071648/angular-js-programmatically-setting-a-form-field-to-dirty
'programing' 카테고리의 다른 글
1 컬렉션 mongodump 사용방법 (0) | 2023.02.28 |
---|---|
도커에 워드프레스(작성 없음) (0) | 2023.02.28 |
goBack()이 라우터 v4에 응답하기 전에 이전 위치를 확인합니다. (0) | 2023.02.28 |
Google Instant는 어떻게 작동합니까? (0) | 2023.02.28 |
Pymongo를 사용하여 컬렉션의 모든 문서 가져오기 (0) | 2023.02.28 |