使用angular比较表中的两个输入字段值

时间:2016-09-28 05:45:08

标签: angularjs

我是angularjs的初学者,我正在尝试创建一个动态表,但使用自定义验证。例如,我有2个输入字段,即totalSalary和养老金支付。支付的养老金不应超过总薪资。我正在尝试为养老金付费字段构建自定义指令但是如何获取totalSalary字段的值来进行比较? 感谢帮助。 阿什利 更新:

这是我根据下一个链接制作的表格。 Dynamic table made so far 以下是我需要比较的两个字段。

 <td><input type="text" class="form-control" ng-model="employee.details.salary" fcsa-number required/></td>
<td><input type="text" class="form-control" ng-model="employee.details.pension" fcsa-number not-greater-than-yearly-sal required/></td>

到目前为止,我所使用的指令如下所示。我得到了养老金1的价值但现在如何获得工资的价值。在离开养老金1的输入时,如果金额大于工资,则应提示用户并清除该值。

angular.module('app').directive("notGreaterThanYearlySal", function () {
  return {
    restrict: "A",
    require: "?ngModel",
    link: function (scope, element, attributes, ngModel) {
      element.bind('blur', function(event){
        alert(element.val());
      });
    }
  };
});

5 个答案:

答案 0 :(得分:0)

使用自定义指令实现的一种方法

例如,我在这里匹配电子邮件:

  <p>Email:<input type="email" name="email1" ng-model="emailReg">
      Repeat Email:<input type="email" name="email2" ng-model="emailReg2"     ng-match="emailReg"></p>

   <span data-ng-show="myForm.emailReg2.$error.match">Emails have to match!</span>

答案 1 :(得分:0)

不使用自定义指令:

  <button ng-click="add()></button>
 <span ng-show="IsMatch">Emails have to match!</span>

   $scope.add = function() {
  if ($scope.emailReg != $scope.emailReg2) {
   $scope.IsMatch=true;
    return false;
   }
   $scope.IsMatch=false;
   }

答案 2 :(得分:0)

我认为这是一种非常巧妙的方式。您可以将ng-max之类的内容设置为第二个输入,并将其值设置为其他输入ng-model。然后根据这个你可以显示一条错误信息。

<form name="numberForm">
  First input:
  <input type="number" name="number1" ng-model="number1">
  Second input:
  <input type="number" name="number2" ng-model="number2" ng-max="number1">
  <span ng-show="numberForm.number2.$error.max">This field should not be larger than the other</span>
</form>

这是一个JSFiddle:https://jsfiddle.net/thepio/dpgfuy06/

答案 3 :(得分:0)

无需指令!

在代码中进行以下更改: -

使用ng-repeat来迭代员工详细信息中的元素数组,如下所示: -

 <div ng-repeat ="details in employee.details">
 </div>

其中所有元素都应放在employee.details数组中

相应地将您的ng模型更改为&#34; details.pension&#34;和&#34; details.salary&#34;

在输入字段下方创建一个div,并在ng-show中指定所需的条件

并显示相同的错误消息。

例如,在您的情况下,它看起来像: -

<div ng-show="details.pension > details.salary">Pension cannot be greater than salary!
</div>

这应该在那里进行验证然后再进行验证。

答案 4 :(得分:-1)

使用自定义指令:

     .directive("compareTo", function () {
return {
    require: "ngModel",
    scope: {
        otherModelValue: "=compareTo"
    },
    link: function (scope, element, attributes, ngModel) {
        ngModel.$validators.compareTo = function (modelValue) {
            return modelValue == scope.otherModelValue;
        };
        scope.$watch("otherModelValue", function () {
            ngModel.$validate();
        });
    }
};
})