我是Angular.js的新手,正在为应用程序开发注册页面。这里我把用户的电话号码作为主键。在用户输入他的电话号码后的注册表中,我正在对数据库进行AJAX调用,以检查号码是否已经存在。我成功地完成了那部分。但是如果用户已经注册,我不知道如何向用户显示错误消息。
我的index.html 代码
<div class="form-group" ng-class="{ 'has-error' : userForm.contactno.$invalid && (userForm.contactno.$dirty || submitted) }">
<label>ContactNo</label>
<input phone type="text" name="contactno" class="form-control" ng-model="user.phone" placeholder="Your Contact No" ng-pattern="/^[789]d{9}$/" maxlength="10">
<p ng-show="userForm.contactno.$error.pattern && (userForm.contactno.$dirty || submitted)" class="help-block">Enter a valid contactno.</p>
</div>
这是我的AJAX调用:
myAppDirectives.
directive('phone', function() {
return {
restrice: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
angular.element(element).bind('blur', function() {
var phnNum = this.value;
$.ajax({
url: 'http://localhost:8087/users/'+phnNum,
dataType: 'application/json',
type: 'GET',
success: function( data, status, headers, cfg ){
console.log("data" +data);
},
error: function( jqXHR, textStatus, errorThrown ){
if(result.responseText.length===0){
console.log("you can register now");
}
else{
console.log("User with this number is already registered");
}
}
});
});
}
提前感谢
在页面中显示错误消息非常容易。只需将错误消息传递到scope并将其显示在相关页面中即可。就像这样。Ajax的Insted在您的angular请求中练习使用$http.post或$http.get。
$scope.checkNumber=function(phnNum){
$http.post('http://localhost:8087/users', phnNum).success(function(data){
if(data == "false"){
$scope.error = 'User with this number is already registere.';
} else {
$scope.submitTrueMessage = 'you can register now';
$scope.error = null;
}
});
};
这就是如何在视图中显示错误消息。
<span style="color:red"> {{error}} </span>
希望这些信息对你有帮助。
如果您想在数据库中存在电话号码时显示警报,则应尝试在api中进行编码。
您可以在回调函数中编写逻辑,即"success"&"错误"。
或者,您也可以使用Angular JS中的ngMessages模块来设计自定义错误消息。
docs.angularjs.org/api/ngMessages
检查电话号码,如果它已经通过数据库中的循环退出,则使用
{{error}}并在if部分和else部分中定义代码部分中的错误以存储电话号码。