我按照解决方案检查数据库中是否已存在用户名:本主题中定义的“angularjs: custom directive to check if a username exists”
在我的情况下,我想在用户想要更新他的数据时付诸实践;当用户想要更改其LASTNAME时,必须启动该脚本。
开头,脚本不应显示错误消息
此处我的控制器:
// MY DIRECTIVE FOR CHECKING IF THE USERNAME IS ALREADY USED
app.directive('usernameAvailable', function($timeout, $q, $http, ContactService) {
return {
restrict: 'AE',
require: 'ngModel',
link: function(scope, elm, attr, model) {
model.interation=0;
model.$asyncValidators.usernameExists = function() {
name= elm.val();
return ContactService.searchContactByName(name).success(function(contact){
$timeout(function(){
if(contact.length >0){
model.$setValidity('usernameExists', contact);
//model.$setValidity('unique', false); // For validation criteria in the form
scope.alreadyExist='true';
scope.contacts = contact;
}else{
model.$setValidity('usernameExists', contact);
//model.$setValidity('unique', true); // For validation criteria in the form
scope.alreadyExist='false';
scope.contacts = null;
}
}, 600);
});
};
}
}
});
app.controller('ctrlEditContacts', function ($scope, $routeParams, ContactService){
// LOAD DATA ABOUT THE USER
ContactService.loadPersonById($routeParams.contactId).success(function(contact){
$scope.contact.ID = contact[0].ID;
$scope.contact.LASTNAME = contact[0].LASTNAME;
$scope.contact.FIRSTNAME = contact[0].FIRSTNAME;
});
});
此处我的模板:
<div class="panel-body">
<form name="ContactForm" class="form-horizontal" role="form" novalidate ng-submit="submitForm(contact)">
<div class="form-group">
<label for="username" class="col-sm-2 control-label">Last Name *</label>
<div class="col-sm-10">
<input type="text" class="form-control"
name="username" maxlength="100" placeholder="Enter Last Name"
required
ng-model="contact.LASTNAME"
username-available
ng-model-options="{ updateOn: 'blur' }">
<div ng-if="ContactForm.$pending.usernameExists">checking....</div>
<div ng-show="alreadyExist=='true'" class="alert alert-info" role="alert" style="margin-top:10px;">
<span class="glyphicon glyphicon-alert" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
Last Name already exists
</div>
</div>
</div>
<div class="form-group">
<label for="txtFirstName" class="col-sm-2 control-label">First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="txtFirstName" maxlength="100" placeholder="Enter First Name" ng-model="contact.FIRSTNAME">
</div>
</div>
目前,该脚本正在运行。 加载页面时,会正确检索和显示有关用户的数据。但脚本同样加载,并显示消息“姓氏已存在”。 所以我想避免这种情况,只有在更新(并且已经使用)姓氏的值时才会显示此消息。
你能告诉我如何更新脚本(我想要的指令)吗?
提前感谢您的帮助。