2016-08-02 64 views
0

我有一個輸入確認電子郵件的兩倍,如何運行customed指令和正常NG-指令還

然而,當我用check-email指令和required驗證不能正常工作了。

有什麼建議嗎?我不希望用戶保持這一領域的空白

HTML

<input type="text" 
     id="confirm_email_booking" 
     name="confirm_email_booking" 
     class="form-control" 
     check-email 
     ng-model="payment_contact.confirm_email_booking" 
    /> 

JS

app.directive('checkEmail', function() { 
    return { 
     require: 'ngModel', 
     link: function(scope, elm, attrs, ctrl) { 
      ctrl.$parsers.unshift(function(viewValue, $scope) { 
       var notMatch = (viewValue != scope.form.email_booking.$viewValue) 
       ctrl.$setValidity('notMatch', !notMatch) 

       return notMatch; 
      }) 
     } 
    } 
}) 
+0

嘛,我看不到任何'required'這裏.. – developer033

+0

你爲什麼不只需添加校驗功能'Ctrl鍵。$ validators'? – MMhunter

回答

0

你可以只檢查是否值是在你的指令目前,如下:

var notMatch = viewValue && viewValue != scope.form.email_booking.$viewValue; 

然後,你可以有這樣的事情:

(function() { 
 
    "use strict"; 
 

 
    angular 
 
    .module('app', []) 
 
    .controller('MainCtrl', MainCtrl) 
 
    .directive('checkEmail', checkEmail); 
 

 
    MainCtrl.$inject = ['$scope']; 
 

 
    function MainCtrl($scope) { 
 

 
    } 
 

 
    function checkEmail() { 
 
    return { 
 
     require: 'ngModel', 
 
     link: function(scope, elm, attrs, ctrl) { 
 
     ctrl.$parsers.unshift(function(viewValue, $scope) { 
 
      var notMatch = viewValue && viewValue != scope.form.email_booking.$viewValue; 
 
      ctrl.$setValidity('notMatch', !notMatch); 
 

 
      return notMatch; 
 
     }) 
 
     } 
 
    } 
 
    } 
 
})();
<!DOCTYPE html> 
 
<html ng-app="app"> 
 

 
<head> 
 
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 
 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css"> 
 
</head> 
 

 
<body ng-controller="MainCtrl"> 
 
    <div class="col-md-12"> 
 
    <form name="form"> 
 
    <input type="text" id="email_booking" name="email_booking" class="form-control" ng-model="payment_contact.email_booking" /> 
 
    <hr> 
 
    <input type="text" id="confirm_email_booking" name="confirm_email_booking" class="form-control" check-email ng-model="payment_contact.confirm_email_booking" required /> 
 
    <span class="text-danger" ng-if="form.confirm_email_booking.$error.required"> 
 
     Required! 
 
    </span> 
 
    <span class="text-danger" ng-if="form.confirm_email_booking.$error.notMatch"> 
 
     NotMatch! 
 
    </span> 
 
    <pre ng-bind="form.confirm_email_booking | json"></pre> 
 
    </form> 
 
    </div> 
 
</body> 
 

 
</html>