2016-05-24 4 views
1

私は角度jを初めて使用しており、ぼかしのフィールドを検証したいと考えています。 ディレクティブが呼び出され、入力された値を検証している値を入力しています。私はこれがぼかしで起こることを望みます。 私はすでに他の関数を呼び出すためにhtmlのon-blurを使用しています。オンブレのぼかしの角度チェック

以下

はディレクティブです:

app.directive("emailCheck", function(){ 
return { 
    require: 'ngModel', 
    link: function (scope, elm, attrs, ctrl) { 
     ctrl.$parsers.unshift(function (viewValue, $scope) { 
      var emailPattern = /\[email protected]\S+\.\S+/; 
      var isEmailValid = emailPattern .test(viewValue) 
      ctrl.$setValidity('emailFormat', isEmailValid); 
      return viewValue; 
     }) 
    } 
}; 
}); 

は、どのように私はここでblurイベントにするためにチェックしますか?

ありがとうございます。

答えて

2

blurイベントをディレクティブにバインドする必要があります。

link: function (scope, elm, attrs, ctrl) { 
    elm.bind('blur',function(){ 
    }) 
} 

var app = angular 
 
    .module('MyApp', [ 
 
    ]) 
 
.controller('Main', ['$scope', function ($scope) { 
 

 
}]) 
 
.directive("emailCheck", function(){ 
 
return { 
 
    require: 'ngModel', 
 
    link: function (scope, elm, attrs, ctrl) { 
 
     elm.bind('blur',function(){ 
 
     alert("test"); 
 
     }) 
 
    } 
 
}; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div class="main-content" ng-app="MyApp" ng-controller="Main as myCtrl"> 
 
     <div> 
 
      <input type="text" ng-model="email" email-check> 
 
    </div> 
 
</div>

1

あなたはディレクティブの内側ぼかしイベントを処理し、以下の方法でそれを処理するためにhtml要素から同じことを削除する必要があります:

app.directive("emailCheck", function(){ 
return { 
    require: 'ngModel', 
    link: function (scope, elm, attrs, ctrl) { 
     elm.on('blur', function() { 
      // @TODO you will have to put your code here to handle this event 
     }); 
    } 
}; 
}); 
このようにしてみてください
2

従来、ディレクティブでngModelを使用すると、どのイベントにフックするかを決めることはありません。 ngModelが接続されているイベントを購読します。これはデフォルトではぼかしだけではありません。

あなたのディレクティブの使用者は次のように、唯一のぼかしに更新するupdateOn: blur``でngModelOptionsを使用することができます。これを試してみてください

<input 
    email-check 
    name="testEmail" ng-model="testEmail" 
    ng-model-options="{ updateOn: 'blur' }"> 

<!-- Note using "updateOn: 'blur'" NOT "updateOn: 'default blur'" --> 

ngModelOptions Docs

0

define(['app'],function(app){ 
app.directive('myDecimals', function() { 
    return { 
    restrict: 'A', 
    link: function(scope, elm, attrs) { 

     elm.bind('blur',function(){ 
      elm.val(elm.val()*1); 
     }); 
    } 
    }; 
}); 
}); 
関連する問題