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から取られました。これらすべてが完全なアプリにどのように適合するかを確認するために、チェックアウトする価値があるかもしれません.