使用$ dirty标志仅在用户与输入交互后显示错误:
<div> <input type="email" name="email" ng-model="user.email" required /> <span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span> </div>
如果只想在用户提交表单后触发错误,可以使用单独的标志变量,如:
<form ng-submit="submit()" name="form" ng-controller="MyCtrl"> <div> <input type="email" name="email" ng-model="user.email" required /> <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required"> Email is required </span> </div> <div> <button type="submit">Submit</button> </div> </form>
function MyCtrl($scope){ $scope.submit = function(){ // Set the 'submitted' flag to true $scope.submitted = true; // Send the form to server // $http.post ... } };
然后,如果所有在ng-showexpression中的JS看起来太多了,你可以将它抽象为一个单独的方法:
function MyCtrl($scope){ $scope.submit = function(){ // Set the 'submitted' flag to true $scope.submitted = true; // Send the form to server // $http.post ... } $scope.hasError = function(field,validation){ if(validation){ return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]); } return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid); }; };
<form ng-submit="submit()" name="form"> <div> <input type="email" name="email" ng-model="user.email" required /> <span ng-show="hasError('email','required')">required</span> </div> <div> <button type="submit">Submit</button> </div> </form>