1

这是我在这个很棒的论坛上的第一个问题。

我需要警告用户为什么他输入的号码无效,但我想每次只打印一条消息。我已经实现了一个解决方案,但它并不是很容易进化。

这是我的 HTML 代码:

<input type="number" name="amountReceived" class="styled" data-ng-model="cashAmountReceived" required>
<div class="error" data-ng-show="cashPaymentForm.amountReceived.$error.required && cashPaymentForm.submitted">Valid amount required</div>
<div class="error" data-ng-show="cashPaymentForm.amountReceived.$error.notEnought && cashPaymentForm.submitted">It's not enought</div>
<div class="error" data-ng-show="cashPaymentForm.amountReceived.$error.negatif && cashPaymentForm.submitted">Positive value only</div>

这是我的控制器代码:

$scope.$watch('cashAmountReceived', function() {

    if(angular.isNumber($scope.cashAmountReceived)){


         var tmp =  $scope.cashAmountReceived.toString();
         tmp = tmp.replace(/(\d{0,9})+\.(\d{0,2}).*/,'$1.$2');
         $scope.cashAmountReceived = parseFloat(tmp);

         if( $scope.cashAmountReceived < 0){
             $scope.cashPaymentForm.amountReceived.$setValidity('negatif', false);
             $scope.cashPaymentForm.amountReceived.$setValidity('notEnought', true);
         }
         else{
             $scope.cashPaymentForm.amountReceived.$setValidity('negatif', true);

             if($scope.cashAmountReceived < $scope.totalProductPrice){
                 $scope.cashPaymentForm.amountReceived.$setValidity('notEnought', false);
             }
             else{
                 $scope.cashPaymentForm.amountReceived.$setValidity('notEnought', true);
             }
         }
     } 
     else{
         $scope.cashPaymentForm.amountReceived.$setValidity('notEnought', true);
         $scope.cashPaymentForm.amountReceived.$setValidity('negatif', true);
     }
});

ng-show由于我的 HTML 页面中的指令,我必须手动管理有效性错误,以确保只打印一个。我想实现一个易于进化的解决方案,以防我需要添加更多验证标准。

我考虑使用优先级管理系统对我的自定义错误做出自己的指令,并与默认错误可能性兼容,但我不知道如何继续。

或者也许我可以将进程留在控制器中并只创建一个名为的自定义错误custom并定义一个名为 whitch 的范围变量errorReason将包含适当的警告消息

我的 HTML 代码中会有类似的内容:

<input type="number" name="amountReceived" class="styled" data-ng-model="cashAmountReceived" required>
<div class="error" data-ng-show="cashPaymentForm.amountReceived.$error.custom && cashPaymentForm.submitted">{{errorReason}}</div>

你们怎么看?

如果我的英语不正确,我深表歉意。

4

0 回答 0