我是 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() 函数。 提前致谢
最佳答案
添加 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">
关于javascript - 如何从 Angular.js 中的 index.html 页面调用指令中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28641645/