您可以将 ng-required="itemForm.name.$invalid" 替换为 required。
这是工作代码。
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});
}
});
}
};
})
小提琴Link