在这里,我使用angularJs创建了一个简单的程序,在这里,当发生错误时,如何专注于特定领域
提前致谢
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.save=function(){
if($scope.firstName != undefined){
if($scope.firstName.length < 3) {
alert("Please Enter More that 3 char");
}
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<form>
<input type="text" ng-model="firstName"/>
<input type="submit" ng-click="save()"/>
</form>
</body>
最佳答案
试试这个,当您尝试提交表单时,它将集中包含错误的元素。
您的html:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<form name="formname" id="form1" novalidate ng-submit="form(formname)">
<input type="text" ng-model="firstName"/>
<input type="submit"/>
</form>
</body>
并在您的控制器中编写此代码
$scope.form = function (form) {
var firstError = null;
if (form.$invalid) {
var field = null, firstError = null;
for (field in form) {
if (field[0] != '$') {
if (firstError === null && !form[field].$valid) {
firstError = form[field].$name;
}
if (form[field].$pristine) {
form[field].$dirty = true;
}
}
}
angular.element('.ng-invalid[name=' + firstError + ']').focus();
return;
} else {
$scope.save()
}
}