angularjs 验证用户名是否重复
对于一个需要验证唯一性的字段
html 代码:
<form class="form-horizontal" novalidate ng-submit="addSendDepartments()" role="form" name="addForm"> <input type="text" ng-model="name" ensure-unique="name" required name="name"/> <span class="error" ng-show="addForm.name.$error.unique">部门名称已存在</span> <span class="error" ng-show="addForm.name.$error.required && addForm.name.$dirty"> 部门名不能为空 </span> <div class="mar-t-20"> <button type="submit" class="btn btn-default btn-enter" ng-disabled="addForm.$invalid">提交</button> <button type="button" class="btn btn-default btn-close" ng-click="addModule.close()">取消</button> </div> </form>
js 代码: 在后台返回的数据为 true 或者 false 时
.directive('ensureUnique', function ($http, optionUrl) { return { require: 'ngModel', link: function (scope, elem, attrs, ctrl) { scope.$watch(attrs.ngModel, function (value) { console.log(value); if (!value) return; $http({ method: 'POST', url: optionUrl.checkName, params: {name: value} }).success(function (data) { ctrl.$setValidity('unique', data); console.log(data); /*return false;*/ }).error(function (data) { ctrl.$setValidity('unique', false); }) }) } } })