[英]How to validate form again when input value is removed in AngularJS
首先,我點擊了沒有值的注冊按鈕,我的自定義指令顯示了正確的警報(使用甜蜜警報)。
當我在填寫第一個輸入后執行相同的操作時也沒有問題。
但是當我填寫第二個輸入並刪除第一個輸入時,
表單驗證忽略了第一個輸入是否為空。
這是我的小提琴。
下面是我的directive
。
.directive('validFocus', function () {
return {
required: 'ngModel',
restrict: 'A',
scope: {
invalidHTML: '&showSwal'
},
link: function (scope, element) {
element.on('submit', function () {
var firstInvalid = element[0].querySelector('.ng-invalid');
if (firstInvalid) {
scope.invalidHTML({html: firstInvalid});
}
});
}
};
})
預先感謝您並修復我的愚蠢問題。 :)
.
.
更新
也許這些圖片可以讓我更容易理解我的目的。
2.刪除第一個輸入值並填充第二個輸入后單擊rigster按鈕
.
.
我期望的是“輸入姓名”。 不是“輸入血型”。 在第二張圖片中。
你可以用 required 替換 ng-required="itemForm.name.$invalid" 。
這是工作代碼。
HTML
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<form role="form" ng-submit="registerItem(itemData)" show-swal="showInvalidMsg(html)" name="itemForm" novalidate valid-focus>
<div>
<label>Name : </label>
<input ng-model="itemData.name" required
name="name"
type="text"
placeholder="Enter Name.">
</div>
<div>
<label>Asset : </label>
<input ng-model="itemData.asset"
required
name="asset"
type="number"
placeholder="Enter Asset.">
</div>
<div>
<label>Select : </label>
<select ng-options="sel.key as sel.value for sel in selectList"
data-ng-model="selectVal"
required
name="some name"
data-ng-change="itemData.select=selectVal">
<option value="">{{addressInfo}}</option>
</select>
</div>
<div>
<label>Blood : </label>
<input ng-model="itemData.blood"
required
name="blood"
type="text"
placeholder="Enter Blood Type.">
</div>
<div>
<label>Color : </label>
<input ng-model="itemData.color"
required
name="color"
type="text"
placeholder="Enter Color.">
</div>
<button type="submit">Register</button>
</form>
</div>
</div>
JS
var MyApp = angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.pageTitle = 'Register New Item';
$scope.addressInfo = 'Choose One';
$scope.isUsed = false;
$scope.selectList = [
{key: 'one', value: '1'},
{key: 'two', value: '2'},
{key: 'three', value: '3'}
];
$scope.showInvalidMsg = function (html) {
console.log(html);
$scope.showAlert(
$scope.pageTitle,
html.placeholder
).then(function () {
html.focus();
});
};
$scope.registerItem = function (itemData) {
if ($scope.itemForm.$valid) {
console.log(itemData);
}
};
$scope.showAlert = function(mTitle, mText){
return swal({
title: mTitle,
text: mText,
type: 'warning',
animation: false,
allowOutsideClick: false
});
};
}])
.directive('validFocus', function () {
return {
required: 'ngModel',
restrict: 'A',
scope: {
invalidHTML: '&showSwal'
},
link: function (scope, element) {
element.on('submit', function () {
var firstInvalid = element[0].querySelector('.ng-invalid');
if (firstInvalid) {
scope.invalidHTML({html: firstInvalid});
}
});
}
};
})
小提琴鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.