7

angular.js は初めてです

 <input type="email" disabled='disabled' name="email" ng-model="userInfo.emailAddress" 
                                    class="input-xlarge settingitem" style="height:30px;"> 

<span ng-show="myForm.email.$error.email" class="help-inline" style="color:red;font-size:10px;">
                                        Not a Valid Email Address</span>

データベースに既に存在するかどうかをサーバーで確認する必要がある電子メール フィールドがあります。

サーバーでチェックするためのAngularディレクティブとサービスを使用してそれを行う方法を誰かが教えてくれますか

4

1 に答える 1

9

NgModelController#$parsersパイプラインにプラグインするディレクティブを作成することをお勧めします( http://docs.angularjs.org/guide/formsの「Custom Validation」を確認してください)。

以下は、そのようなディレクティブのスケッチです。

.directive('uniqueEmail', ["Users", function (Users) {
  return {
    require:'ngModel',
    restrict:'A',
    link:function (scope, el, attrs, ctrl) {

      //TODO: We need to check that the value is different to the original

      //using push() here to run it as the last parser, after we are sure that other validators were run
      ctrl.$parsers.push(function (viewValue) {

        if (viewValue) {
          Users.query({email:viewValue}, function (users) {
            if (users.length === 0) {
              ctrl.$setValidity('uniqueEmail', true);
            } else {
              ctrl.$setValidity('uniqueEmail', false);
            }
          });
          return viewValue;
        }
      });
    }
  };
}])

メールUsers.queryが一意かどうかを確認するための非同期呼び出しです。もちろん、これをバックエンドへの呼び出しに置き換える必要があります。

完了すると、このディレクティブは次のように使用できます。

<input type="email" ng-model="user.email" unique-email>

このディレクティブの例は、一部の AngularJS コミュニティ メンバーが一般的なユース ケースを説明するためにまとめようとしているangular-appから取られました。これらすべてが完全なアプリにどのように適合するかを確認するために、チェックアウトする価値があるかもしれません.

于 2013-02-20T11:05:05.097 に答える