form.name.$valid是否有效
form.name.$invalid 是否无效
form.name.$error错误的集合
form.name.$error.required
form.name.$error.email
控制submit按钮是否disabled 启用ng-disabled="form.$invalid"
下面是验证是否用户名唯一的简单写法
<!DOCTYPE html> <html> <head> <title></title> <script src="angular.min.js" type="text/javascript"></script> </head> <body ng-app="formTest" ng-controller="formController"> <form name="myForm" ng-submit="show()"> <input name="personName" required ng-model="person.name" ensure-Unique="personName"/> <span></span> <input type="submit" ng-disabled="myForm.$invalid"/> </form> <script> var formTest = angular.module("formTest", []); formTest.controller("formController", function ($scope) { $scope.person = { email: "", name: "Jackey" }; $scope.show = function () { //alert($scope.person.name); console.log(myForm.personName.$error) }; }).directive("ensureUnique", function ($http) { return { require: "ngModel", link: function (scope, element, attrs) { scope.$watch(attrs.ngModel, function () {
//$http..... console.log(scope.person.name); element.next("span").text(scope.person.name);//显示是否存在唯一 }); } }; }); </script> </body> </html>
再修改一下
<!DOCTYPE html> <html> <head> <title></title> <script src="angular.min.js" type="text/javascript"></script> </head> <body ng-app="formTest" ng-controller="formController"> <form name="myForm" ng-submit="show()"> <input name="personName" required ng-model="person.name" ensure-Unique="personName"/> <span></span> <input type="submit" ng-disabled="myForm.$invalid"/> </form> <script> var formTest = angular.module("formTest", []); formTest.controller("formController", function ($scope) { $scope.person = { email: "", name: "" }; $scope.show = function () { //alert($scope.person.name); console.log(myForm.personName.$error) }; }).directive("ensureUnique", function () { return { require: "ngModel", link: function (scope, element, attrs) { scope.$watch(attrs.ngModel, function (n) { if (!n) return; console.log(n); element.next("span").text(scope.person.name); //显示是否存在唯一 }); } }; }); </script> </body> </html>