角指令的唯一的用户名指令、用户名

2023-09-13 04:21:26 作者:孤傲あ

我看着一堆angularjs指令检查用户名的唯一性,决定尝试最简单的实现。它不会是我想要的,但未必真的是地道的角度。这里是表单元素:

I looked at a bunch of angularjs directives checking for uniqueness of a username and decided to try for the simplest implementation. It does what I want but may not really be 'idiomatic' angular. Here is the form element:

<input type="text"
    name="username"
    ng-model="form.username"
    unique-username=""
    required
/>
<span class="hide-while-in-focus" ng-show="thisform.username.$error.unique">Username taken!</span>

和这里的指令:

.directive('uniqueUsername', function($http) {
      return {
           restrict: 'A',
           require: 'ngModel',
           link: function (scope, element, attrs, ngModel) {
                element.bind('blur', function (e) {
                     ngModel.$setValidity('unique', true);

                     $http.get("/api/checkUnique/" + element.val()).success(function(data) {
                          if (data) {
                              ngModel.$setValidity('unique', false);
                          }
                     });
                });
           }
      };
})

和前任pressjs通话

And the expressjs call

if (data) {
      console.log("found " + data.username);
      return res.send(data.username);
}
else {
      console.log("not found");
      return res.send(404);
}

我想AP preciate为什么这是好还是坏,如果可能的模型使用$ scope.watch修订任何反馈。

I would appreciate any feedback on why this is good or bad and if possible a revision that uses $scope.watch on the model.

推荐答案

一个小的改善 - 我会建议增加一个$装载标志。因为它是一个异步请求,它使需要时间它返回:

One small improvement - I would recommend adding a $loading flag. Since it is an asynchronous request, it make take time for it to return:

directive('uniqueUsername', function($http) {
      return {
           restrict: 'A',
           require: 'ngModel,^form',
           link: function (scope, element, attrs, ngModel) {
                element.bind('blur', function (e) {
                     ngModel.$loading = true;

                     $http.get("/api/checkUnique/" + element.val()).success(function(data) {
                        ngModel.$loading = false;
                        ngModel.$setValidity('unique', !data);
                     });
                });
           }
      };
})

然后就可以显示等待消息(或微调),而其等待异步调用返回:

Then you can show a wait message (or spinner) while its waiting for the async call to return:

<input type="text"
    name="username"
    ng-model="form.username"
    unique-username=""
    required
/>
<span ng-show="thisform.username.$loading">Loading...</span>
<span class="hide-while-in-focus" 
     ng-show="thisform.username.$error.unique">Username taken!</span>

如果你想让它停止表单提交,直到异步调用返回的话,我会建议做$加载有效性标志(即$ setValidity('负荷',真/假))

If you want it to stop form submission until the async call returns, then I would suggest making $loading a validity flag (i.e. $setValidity('loading', true/false))