Angular.js와 부트스트랩 폼 검증 스타일 조정
저는 Angular with Bootstrap을 사용하고 있습니다.다음은 참조용 코드입니다.
<form name="newUserForm" ng-submit="add()" class="" novalidate>
<input type="text" class="input" ng-model="newUser.uname" placeholder="Twitter" ng-pattern="/^@[A-Za-z0-9_]{1,15}$/" required></td>
<button type="submit" ng-disabled="newUserForm.$invalid" class="btn btn-add btn-primary">Add</button>
</form>
부트스트랩에 비활성 필드의 스타일이 있습니다.input:invalid {.... }필드가 비어 있을 때 이 값이 표시됩니다.이제 Angular를 통해 패턴 매칭도 할 수 있게 되었습니다.이로 인해 ":invalid"가 오프인데 ".ng-invalid"가 온일 때 이상한 케이스가 생성됩니다.이 경우 ".ng-invalid" 클래스에 부트스트랩 CSS 클래스를 재실장해야 합니다.
두 가지 방법이 있는데 둘 다 문제가 있어요
- Angular가 "ng-valid" 대신 몇 가지 사용자 지정 클래스 이름을 사용하도록 합니다(이 방법을 모르겠습니다).
- html5 검증을 무효로 합니다(폼태그 내의 "novalidate" Atribute는 그렇게 해야 한다고 생각했지만 어떤 이유로 동작하지 않았습니다).
Angular-Bootstrap 명령어에서는 스타일링을 커버하지 않습니다.
스타일링에는 Bootstrap의 "error" 클래스를 사용합니다.코드를 적게 쓸 수 있습니다.
<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid}">
<label>Name</label>
<input type="text" name="name" ng-model="project.name" required>
<span ng-show="myForm.name.$error.required" class="help-inline">
Required</span>
</div>
</form>
편집: 다른 답변과 코멘트가 지적하듯이 Bootstrap 3에서는 클래스가 "error"가 아닌 "has-error"가 됩니다.
부트스트랩3에서는 클래스가 변경되었습니다.
<form class="form-horizontal" name="form" novalidate ng-submit="submit()" action="/login" method="post">
<div class="row" ng-class="{'has-error': form.email.$invalid, 'has-success': !form.email.$invalid}">
<label for="email" class="control-label">email:</label>
<div class="col">
<input type="email" id="email" placeholder="email" name="email" ng-model="email" required>
<p class="help-block error" ng-show="form.email.$dirty && form.email.$error.required">please enter your email</p>
<p class="help-block error" ng-show="form.email.$error.email">please enter a valid email</p>
...
주위의 따옴표를 주의해 주세요.'has-error'그리고.'has-success': 찾는 데 시간이 걸렸어요...
또 다른 솔루션:전환되는 지시문 작성has-error자녀 입력에 따른 클래스.
app.directive('bsHasError', [function() {
return {
restrict: "A",
link: function(scope, element, attrs, ctrl) {
var input = element.find('input[ng-model]');
if (input.length) {
scope.$watch(function() {
return input.hasClass('ng-invalid');
}, function(isInvalid) {
element.toggleClass('has-error', isInvalid);
});
}
}
};
}]);
템플릿으로 간단하게 사용
<div class="form-group" bs-has-error>
<input class="form-control" ng-model="foo" ng-pattern="/.../"/>
</div>
@farincz의 답변에 대한 약간의 개선.지시가 여기서 가장 좋은 방법이라는 것에 동의하지만, 나는 모든 것에 대해 그것을 반복하고 싶지 않다..form-group그래서 코드를 업데이트하여 다음 중 하나에 추가할 수 있도록 했습니다..form-group또는 부모에게<form>요소(이것에 의해, 포함되는 모든 요소에 추가됩니다)..form-group요소):
angular.module('directives', [])
.directive('showValidation', [function() {
return {
restrict: "A",
link: function(scope, element, attrs, ctrl) {
if (element.get(0).nodeName.toLowerCase() === 'form') {
element.find('.form-group').each(function(i, formGroup) {
showValidation(angular.element(formGroup));
});
} else {
showValidation(element);
}
function showValidation(formGroupEl) {
var input = formGroupEl.find('input[ng-model],textarea[ng-model]');
if (input.length > 0) {
scope.$watch(function() {
return input.hasClass('ng-invalid');
}, function(isInvalid) {
formGroupEl.toggleClass('has-error', isInvalid);
});
}
}
}
};
}]);
@Andrew Smith의 답변에 대한 약간의 개선.입력 요소 변경 및 사용require키워드를 지정합니다.
.directive('showValidation', [function() {
return {
restrict: "A",
require:'form',
link: function(scope, element, attrs, formCtrl) {
element.find('.form-group').each(function() {
var $formGroup=$(this);
var $inputs = $formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');
if ($inputs.length > 0) {
$inputs.each(function() {
var $input=$(this);
scope.$watch(function() {
return $input.hasClass('ng-invalid');
}, function(isInvalid) {
$formGroup.toggleClass('has-error', isInvalid);
});
});
}
});
}
};
}]);
@farincz에게 좋은 답변을 주셔서 감사합니다.다음은 사용 사례에 맞게 몇 가지 수정한 내용입니다.
이 버전에서는, 다음의 3개의 디렉티브가 있습니다.
bs-has-successbs-has-errorbs-has(나머지 2개를 함께 사용하고 싶을 때 편리함)
수정 사항:
- 폼 필드가 더러울 때만 표시되도록 체크 표시(즉, 누군가와 상호작용할 때까지 표시되지 않음)를 추가했습니다.
- 전달된 문자열 변경
element.find()jQuery를 사용하지 않는 사용자의 경우element.find()Angular의 jQLite에서는 tagname에 의한 요소 찾기만 지원합니다. - 선택 상자 및 텍스트 영역 지원이 추가되었습니다.
element.find()in a a a a$timeout자식을 DOM에 않은 를 들어 요소의 가 DOM으로 되어 있는 를 지원한다.ng-if를 참조해 주세요.- .
if배열의 식(표현)if(input)from @farincz의 답변은 항상 true를 반환합니다.element.find()jQuery ★★★★★★★★★★★★★★★★」
누가 이걸 유용하게 찾았으면 좋겠어!
angular.module('bs-has', [])
.factory('bsProcessValidator', function($timeout) {
return function(scope, element, ngClass, bsClass) {
$timeout(function() {
var input = element.find('input');
if(!input.length) { input = element.find('select'); }
if(!input.length) { input = element.find('textarea'); }
if (input.length) {
scope.$watch(function() {
return input.hasClass(ngClass) && input.hasClass('ng-dirty');
}, function(isValid) {
element.toggleClass(bsClass, isValid);
});
}
});
};
})
.directive('bsHasSuccess', function(bsProcessValidator) {
return {
restrict: 'A',
link: function(scope, element) {
bsProcessValidator(scope, element, 'ng-valid', 'has-success');
}
};
})
.directive('bsHasError', function(bsProcessValidator) {
return {
restrict: 'A',
link: function(scope, element) {
bsProcessValidator(scope, element, 'ng-invalid', 'has-error');
}
};
})
.directive('bsHas', function(bsProcessValidator) {
return {
restrict: 'A',
link: function(scope, element) {
bsProcessValidator(scope, element, 'ng-valid', 'has-success');
bsProcessValidator(scope, element, 'ng-invalid', 'has-error');
}
};
});
사용방법:
<!-- Will show success and error states when form field is dirty -->
<div class="form-control" bs-has>
<label for="text"></label>
<input
type="text"
id="text"
name="text"
ng-model="data.text"
required>
</div>
<!-- Will show success state when select box is anything but the first (placeholder) option -->
<div class="form-control" bs-has-success>
<label for="select"></label>
<select
id="select"
name="select"
ng-model="data.select"
ng-options="option.name for option in data.selectOptions"
required>
<option value="">-- Make a Choice --</option>
</select>
</div>
<!-- Will show error state when textarea is dirty and empty -->
<div class="form-control" bs-has-error>
<label for="textarea"></label>
<textarea
id="textarea"
name="textarea"
ng-model="data.textarea"
required></textarea>
</div>
이 모든 것을 묶은 Gilherme의 bower 패키지를 설치할 수도 있습니다.
스타일링이 문제지만 네이티브 검증을 무효로 하고 싶지 않다면 자신의 스타일링을 더 구체적인 스타일로 덮어쓰는 것은 어떨까요?
input.ng-invalid, input.ng-invalid:invalid {
background: red;
/*override any styling giving you fits here*/
}
CSS 셀렉터의 고유성으로 문제를 캐스케이드화!
Jason Im의 답변에 대한 나의 개선은 다음과 같은 두 가지 새로운 디렉티브인 show-validation-errors와 show-validation-error를 추가합니다.
'use strict';
(function() {
function getParentFormName(element,$log) {
var parentForm = element.parents('form:first');
var parentFormName = parentForm.attr('name');
if(!parentFormName){
$log.error("Form name not specified!");
return;
}
return parentFormName;
}
angular.module('directives').directive('showValidation', function () {
return {
restrict: 'A',
require: 'form',
link: function ($scope, element) {
element.find('.form-group').each(function () {
var formGroup = $(this);
var inputs = formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');
if (inputs.length > 0) {
inputs.each(function () {
var input = $(this);
$scope.$watch(function () {
return input.hasClass('ng-invalid') && !input.hasClass('ng-pristine');
}, function (isInvalid) {
formGroup.toggleClass('has-error', isInvalid);
});
$scope.$watch(function () {
return input.hasClass('ng-valid') && !input.hasClass('ng-pristine');
}, function (isInvalid) {
formGroup.toggleClass('has-success', isInvalid);
});
});
}
});
}
};
});
angular.module('directives').directive('showValidationErrors', function ($log) {
return {
restrict: 'A',
link: function ($scope, element, attrs) {
var parentFormName = getParentFormName(element,$log);
var inputName = attrs['showValidationErrors'];
element.addClass('ng-hide');
if(!inputName){
$log.error("input name not specified!")
return;
}
$scope.$watch(function () {
return !($scope[parentFormName][inputName].$dirty && $scope[parentFormName][inputName].$invalid);
},function(noErrors){
element.toggleClass('ng-hide',noErrors);
});
}
};
});
angular.module('friport').directive('showValidationError', function ($log) {
return {
restrict: 'A',
link: function ($scope, element, attrs) {
var parentFormName = getParentFormName(element,$log);
var parentContainer = element.parents('*[show-validation-errors]:first');
var inputName = parentContainer.attr('show-validation-errors');
var type = attrs['showValidationError'];
element.addClass('ng-hide');
if(!inputName){
$log.error("Could not find parent show-validation-errors!");
return;
}
if(!type){
$log.error("Could not find validation error type!");
return;
}
$scope.$watch(function () {
return !$scope[parentFormName][inputName].$error[type];
},function(noErrors){
element.toggleClass('ng-hide',noErrors);
});
}
};
});
})();
오류 컨테이너에 show-validation-errors를 추가하여 폼필드 유효성에 따라 컨테이너를 표시하거나 숨길 수 있습니다.
및 show-validation-error는 특정 유형의 해당 형식 필드의 유효성을 기반으로 요소를 표시하거나 숨깁니다.
사용 목적의 예:
<form role="form" name="organizationForm" novalidate show-validation>
<div class="form-group">
<label for="organizationNumber">Organization number</label>
<input type="text" class="form-control" id="organizationNumber" name="organizationNumber" required ng-pattern="/^[0-9]{3}[ ]?[0-9]{3}[ ]?[0-9]{3}$/" ng-model="organizationNumber">
<div class="help-block with-errors" show-validation-errors="organizationNumber">
<div show-validation-error="required">
Organization number is required.
</div>
<div show-validation-error="pattern">
Organization number needs to have the following format "000 000 000" or "000000000".
</div>
</div>
</div>
</form>
답장은 늦었지만 마음에 드셨으면 좋겠습니다.
CSS 선택, 날짜, 비밀번호 등 다른 유형의 컨트롤을 추가할 수 있습니다.
input[type="text"].ng-invalid{
border-left: 5px solid #ff0000;
background-color: #FFEBD6;
}
input[type="text"].ng-valid{
background-color: #FFFFFF;
border-left: 5px solid #088b0b;
}
input[type="text"]:disabled.ng-valid{
background-color: #efefef;
border: 1px solid #bbb;
}
HTML: ng-required 이외의 컨트롤에 아무것도 추가할 필요가 없습니다.
<input type="text"
class="form-control"
ng-model="customer.ZipCode"
ng-required="true">
한번 써보고 컨트롤로 텍스트를 입력해보세요.정말 편리하고 멋져요.
바이올린 없이는 확실히 알 수 없지만 angular.js 코드를 보면 클래스를 대체하지 않고 자신의 클래스를 추가하고 삭제할 뿐입니다.따라서 부트스트랩 UI 스크립트에 의해 동적으로 추가되는 부트스트랩클래스는 angular에 의해 변경되지 않아야 합니다.
즉, Angular와 동시에 Bootstrap의 JS 기능을 검증에 사용하는 것은 의미가 없습니다. Angular만 사용합니다.부트스트랩 스타일과 각도 JS를 사용하는 것을 추천합니다.즉, 커스텀 검증 디렉티브를 사용하여 부트스트랩 css 클래스를 요소에 추가합니다.
<div class="form-group has-feedback" ng-class="{ 'has-error': form.uemail.$invalid && form.uemail.$dirty }">
<label class="control-label col-sm-2" for="email">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" ng-model="user.email" name="uemail" placeholder="Enter email" required>
<div ng-show="form.$submitted || form.uphone.$touched" ng-class="{ 'has-success': form.uemail.$valid && form.uemail.$dirty }">
<span ng-show="form.uemail.$valid" class="glyphicon glyphicon-ok-sign form-control-feedback" aria-hidden="true"></span>
<span ng-show="form.uemail.$invalid && form.uemail.$dirty" class="glyphicon glyphicon-remove-circle form-control-feedback" aria-hidden="true"></span>
</div>
</div>
</div>
Angular의 이름을 들어본 적이 없는 매우 오래된 질문 답변 줄임말이라는 것을 알고 있습니다.JS 자체 :-)
그러나 깨끗하고 자동화된 방식으로 Angular + Bootstrap 폼 검증을 원하는 다른 사용자를 위해 HTML이나 Javascript를 변경하지 않고 이를 실현하기 위한 매우 작은 모듈을 작성했습니다.
다음은 3가지 간단한 단계입니다.
- Bower 경유
bower install bootstrap-angular-validation --save - 파일 「」을 합니다.
<script src="bower_components/bootstrap-angular-validation/dist/bootstrap-angular-validation.min.js"></script> - 를 합니다.
bootstrap.angular.validation어플리케이션에 접속하면 끝!!
이것은 부트스트랩3에서 동작하며 jQuery는 필요 없습니다.
이는 jQuery 검증 개념을 기반으로 합니다.이 모듈에서는 검증 오류에 대한 몇 가지 추가 검증 및 일반적인 일반 메시지를 제공합니다.
언급URL : https://stackoverflow.com/questions/14348384/reconcile-angular-js-and-bootstrap-form-validation-styling
'codememo' 카테고리의 다른 글
| react-passion vs react-passion-dom, 어느 한쪽을 사용할 것인가? (0) | 2023.03.04 |
|---|---|
| 스프링 Application Context를 닫는 방법 (0) | 2023.03.04 |
| 컬럼이 있는데 ORA-00904가 있는 이유는 무엇입니까? (0) | 2023.03.04 |
| Flask jsonify가 데이터를 정렬하지 못하도록 합니다. (0) | 2023.03.04 |
| Angular에서 $resource 메서드에 대한 콜백을 추가하는 방법JS (0) | 2023.03.04 |