나는 한동안 인터넷 검색을 해왔고 내 특정 사례에 대한 좋은 답변을 찾을 수없는 것 같습니다. 실시간 유효성 검사를 수행하는 방법을 찾았지만 사용자가 "제출"을 클릭 한 후이를 사용자 지정 유효성 검사와 결합하고 싶습니다. 유효하지 않은 경우에도 사용자가 제출을 클릭하도록 허용하고 싶지만 코드에서 제출을 취소하겠습니다. 다음 코드를 사용하십시오.
<form name="cashForm" id="cashForm" novalidate>
<input type="text" id="name" required /> //
<input type="number" placeholder="Tax: " required name="tax" id="tax" />
<input type="number" placeholder="Tip: " required name="tip" id="tip" />
<button ng-click="submission()" ng-disabled="paymentForm.$invalid">Submit</button>
</form>
//inside controller
this.submission = function() {
//check if tip + tax is over 20
//prevent form and show error message if not
//otherwise allow default behavior
}
따라서 세금 / 팁이 10 이상인 경우에만 양식을 실제로 제출하고 싶습니다.이를 확인하려면 어떻게해야하며 요구 사항을 충족하지 않는 경우 양식 제출을 방지하려면 어떻게해야합니까? 또한이 로직을 컨트롤러에 넣을까요?
당신이 나에게 추구하는 것과 매우 비슷해 보입니다. 몇 가지만 ...
ng-model
입력 컨트롤에 지시문을 추가 하여 컨트롤러에서 선택하고 사용할 수있는 양방향 데이터 바인딩을 만듭니다.
<form name="cashForm" id="cashForm" novalidate>
<input id="name" name="name" type="text" ng-model="nameValue" required />
<input id="tax" name="tax" type="number" ng-model="taxValue" placeholder="Tax: " required />
<input id="tip" name="tip" type="number" ng-model="tipValue" placeholder="Tip: " required />
<button
ng-click="submission()"
ng-disabled="paymentForm.$invalid">
Submit
</button>
$scope
컨트롤러에 삽입 ng-model
하여 컨트롤러의 submission
메서드 에서 이러한 바인딩 을 선택할 수 있습니다 .
function submission() {
$scope.errorMsg = "";
if ($scope.taxValue <= 10) {
$scope.errorMsg = "tax not greater than 10";
return;
}
if ($scope.tipValue <= 10) {
$scope.errorMsg = "tip not greater than 10";
return;
}
// If you reached here your post-click validation passed,
// so continue to submit the data...
}
그런 다음 오류 메시지를 ng-if
강조하는 css 클래스와 함께 지시문을 사용하여 오류 메시지를 표시 할 수 있습니다 .
<div ng-if="!!errorMessage" class="text-danger">
{{ errorMessage }}
</div>
마지막으로 $scope
컨트롤러에서 사용 을 시작하면 사용의 악영향에 대해 읽고 $scope
대신 컨트롤러로서의 구문으로 전환하는 것을 고려할 수 있습니다. John Papa의 블로그 게시물 AngularJS의 Controller As 및 vm 변수 확인
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다