我是Angular.js的新手,所以我在从index.html调用指令函数时遇到问题。
当用户输入他的电话号码时,我必须在Directives.js中调用函数来验证该号码是否已经存在。但我没有得到如何调用该函数。
我的html页面
<div class="form-group" ng-class="{ 'has-error' : userForm.contactno.$invalid && (userForm.contactno.$dirty || submitted) }">
<label>ContactNo</label>
<input 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>
我的Directive.js文件:
myAppDirectives.
directive('phone', function() {
return {
restrice: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
console.log("test1");
angular.element(element).bind('blur', function() {
var phnNum = this.value;
$.ajax({
url: 'http://localhost:8989/users/'+phnNum,
dataType: 'application/json',
type: 'GET',
success: function( data, status, headers, cfg ){
console.log("test2");
console.log("data" +data);
console.log(jqXHR.responseText);
},
error: function( jqXHR, textStatus, errorThrown ){
console.log("on success");
var result=jqXHR;
//console.log("check" +result.responseText);
console.log(jqXHR);
console.log(result.responseText.length);
if(result.responseText.length===0){
console.log("you can register now");
}
else{
console.log("User with this number is already registered");
}
}
});
});
}
}
});
任何人都可以帮助我如何在我的html页面的指令中调用phone()函数。 提前致谢
答案 0 :(得分:2)
将phone
指令添加到<input>
元素
<input phone type="text" name="contactno" class="form-control" ng-model="user.phone" placeholder="Your Contact No" ng-pattern="/^[789]\d{9}$/" maxlength="10">
答案 1 :(得分:1)
您可以将指令手机作为属性放在输入框中: - )
<input phone type="text" name="contactno" class="form-control" ng-model="user.phone" placeholder="Your Contact No" ng-pattern="/^[789]\d{9}$/" maxlength="10">
但是,如果您希望asyn调用使用$ http作为角度js中的本机服务,那么不使用$ .ajax这不是一个角度函数。
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});