2015-07-06 25 views
0

當用戶輸入他的電子郵件時,我將它發送到服務器以檢查它是否正在使用中,如果我的服務器響應爲錯誤我想將表單設置爲無效並且目前消息「emailInUse」

我的指令

ctrl.$asyncValidators.email = function(ctrl, viewValue) { 
      return registerResource.emailAvailable.save({"email":viewValue}).$promise.then(
        function success(response) { 
         // Set the form valid 
        }, 
        function error(response) { 
         // Set the form invalid 
        }); 
     }; 

我的模板

<form name="registerForm" ng-submit="vm.register()" role="form"> 
    <div class="form-group"> 
     <div> 
      <input type="email" 
        placeholder="email" 
        name="email" 
        class="form-control" 
        ng-model="vm.email" 
        email-available 
        ng-minlength=4 ng-maxlength=50 required/> 

      <div ng-messages="registerForm.email.$error"> 
       <div ng-message="required"> 
        You forgot to enter your email address... 
       </div> 
       <div ng-message="email"> 
        You did not enter your email address correctly... 
       </div> 
       <div ng-message="emailInUse"> 
        You did not enter your email address correctly... 
       </div> 
      </div> 
     </div> 
    </div> 

回答

2

你需要建立一個延遲執行對象,並解決或拒絕根據您的資源能夠成功, r錯誤情況。

我拿了https://docs.angularjs.org/guide/forms的示例代碼,並將其更改了一些以匹配您的代碼。在這裏看到:

app.directive('emailAvailable', function($q, $timeout) { 
    return { 
    require: 'ngModel', 
    link: function(scope, elm, attrs, ctrl) { 

     ctrl.$asyncValidators.emailInUse = function(modelValue, viewValue) { 

     var def = $q.defer(); 

     registerResource.emailAvailable.save({"email":viewValue}).$promise.then(
      function success(response) { 
       // Set the form valid 
       def.resolve(); 
      }, 
      function error(response) { 
       // Set the form invalid 
       def.reject(); 
      }); 

     return def.promise; 
     }; 
    } 
    }; 
}); 

我已經改變了角的例子plnkr以獲得更好的理解:

http://plnkr.co/edit/bfSUcqJONz5QAg6vnZ7O?p=preview

提示:它採用了$超時而不是一個HTTP調用到後端。但是,如果您輸入其中一個名稱var usernames = ['Jim', 'John', 'Jill', 'Jackie'];,則會顯示您已用於用戶名的延遲時間爲2秒。

+0

@ alexander-gorelik我的回答對你有幫助嗎? – ilmgb