簡體   English   中英

AngularJS:模糊事件未在表單驗證的指令中觸發

[英]AngularJS: blur event not firing in directive for form validation

使用Angular,我正在編寫一個注冊表單,其中還包含用戶名的輸入字段。 我寫了一個指令,用於在字段模糊時檢查服務器端的“唯一性”用戶名。

這是我的Angular代碼:

App.directive('usernameCheck', ['$http', function ($http) {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            elem.on('blur', function (evt) {          
                scope.$apply(function () {
                    $http({
                        method: 'POST',
                        url: '/usernameCheck/', <-- NEVER ACCESSED!?
                        data: {'username' : $scope.userName}
                    }).success(function(data, status, headers, config) {
                        ctrl.$setValidity('unique', data.status);
                    });
                });
            });  
        }
    }
}]);

和HTML表單輸入元素:

<input type="text" class="form-control" ng-model="userName" name="userName" username-check required>

由於一些奇怪的原因,該指令似乎不起作用。 沒有出現JS錯誤,但模糊元素沒有觸發 - 根據Firebug,從不調用服務器路徑“/ usernameCheck”。 我錯過了什么?

嘗試使用ng-blur方法(簡單的通用示例):

app.directive('directiveName', function () {
  return {
    restrict: 'E',
    scope: {
      ngBlur: '&'
    },
    link:function(scope){    
      scope.onBlur = function(ev){
        console.log(ev);
      }    
   },    
   template: '<input ng-blur="onBlur($event)"></input>'
 }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM