如何在 Angular.js 中的 index.html 页面的指令中调用函数

How to call a function in directives from index.html page in Angular.js

我是 Angular.js 的新手,所以我在从 index.html 的指令中调用函数时遇到问题。

当用户输入他的 phone 号码时,我必须调用 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">

您可以将指令 phone 作为输入框的属性:-)

<input phone type="text" name="contactno" class="form-control" ng-model="user.phone" placeholder="Your Contact No" ng-pattern="/^[789]\d{9}$/" maxlength="10">

但是不要使用 $.ajax 它不是 angular 函数如果你想异步调用使用 $http 是 angular js 中的本地服务.

$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.
  });

Doc