0

試圖添加一個asyncvalidator到我的自定義用戶名驗證器。但它輸出錯誤:

TypeError:無法設置屬性「用戶名」未定義。

如何讓asyncvalidator定義?我以爲我會自動由NgModel控制器?

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
angular.module('myApp.commonDirectives', ['myApp.services']).directive('username', ['UsernameService',function(UsernameService){ 
 
\t 
 
\t return { 
 
\t \t 
 
\t  restrict: 'A', 
 
\t  require: "ngModel", 
 
\t  scope: { 
 
\t   hasFocus: "=username" 
 
\t   
 
\t  }, 
 
\t  link: function(scope, element, attrs, ctrl) { 
 
\t  
 
\t   scope.$watch('hasFocus', function(hasFocus) { 
 
\t    if(angular.isDefined(hasFocus)) { 
 

 
\t     // on blur 
 
\t     if(!hasFocus) { 
 
\t      
 
\t     
 
\t      ctrl.$validated=false; 
 
\t      ctrl.$asyncValidators.username = function(value){ 
 
\t      UsernameService.validate(value) 
 
\t       .then(function(resolvedData) { 
 
\t        if(resolvedData) { 
 
\t       
 
\t        \t ctrl.$validated=true; 
 
\t         ctrl.$setValidity('checking', true); 
 
// \t         ctrl.$setValidity('username', true); 
 
\t        } 
 
\t        else { 
 
\t       
 
\t        \t ctrl.$validated=true; 
 
\t         ctrl.$setValidity('checking', false); 
 
// \t         ctrl.$setValidity('username', false); 
 
\t        } 
 
\t       } 
 
\t      ); 
 
\t     } 
 
\t     } 
 
\t     
 
\t     // on focus 
 
\t     else { 
 
\t      ctrl.$setValidity('username', true); 
 
\t      ctrl.$setValidity('checking', true); 
 
\t     } 
 
\t    } 
 
\t    
 
\t   }); 
 
\t  } 
 

 
\t } 
 
}])

+0

'asyncValidators'是從角1.3 – Dieterg

+0

^難以置信的幫助評論的一個新功能.. .. –

回答

-1
try something like this : 

angular.module('myModule').directive('usernameValidator', function($http, $q) { 
    return { 
     require: 'ngModel', 
     link: function(scope, element, attrs, ngModel) { 
      ngModel.$asyncValidators.username = function(modelValue, viewValue) { 
       return $http.post('/username-check', {username: viewValue}).then(
        function(response) { 
         if (!response.data.validUsername) { 
          return $q.reject(response.data.errorMessage); 
         } 
         return true; 
        } 
       ); 
      }; 
     } 
    }; 
}); 
+0

所有你在那裏做的是複製的例子angular js文檔。我想繼續使用Restangular插件,如果我可以將其抽象爲UsernameService。 爲什麼我的代碼不起作用,請點擊上面的代碼? 感謝您提供任何幫助,您可以提供 – user1782673