我正在对required进行简单验证,但无法找到错误输入或点击提交的ng-Message。有人可以帮我解决我错在哪里吗?
HTML:
<html>
<head>
<!-- Script Files -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<form name="form1" id="form1" novalidate>
<input type="text" name="age" ng-minlength="3" required/>
<div ng-messages="form1.age.$error" ng-show="(form1.age.$error.required || form1.age.$error.minlength) && (form1.age.$touched || form1.$submitted) " >
<div ng-message="required">This is required</div>
<div ng-message="minlength">Length is too less</div>
</div>
<a data-ng-click="submit(form1.$invalid)">Click</a>
</form>
<script>
//module declaration
var app = angular.module('myApp', ['ngMessages']);
//controller declaration
app.controller('myCtrl', function($scope) {
var submit = function(invalid){
if(invalid) return;
}
});
</script>
</body>
</html>
答案 0 :(得分:4)
您的年龄输入没有ng-model
。验证aláminlength仅在ng-model
存在时才有效:
<input type="text" name="age" ng-model="age" ng-minlength="3" required/>
这是由于验证器的工作原理。当$ valid为false时,您会注意到未设置ng-model。文档中也总是有一个提示:https://docs.angularjs.org/api/ng/directive/ngMinlength
同样ng-model
不必与字段名称相同。