【问题标题】:How I can transform a jQuery function in one AngularJS directive?如何在一个 AngularJS 指令中转换 jQuery 函数?
【发布时间】:2016-02-28 17:12:37
【问题描述】:

我必须使用指令验证表单,以便 AngularJS 能够启用或禁用提交表单按钮。

我在 jQuery 中有一个函数,但我需要 AngularJS 监视这个行为。

此功能比较输入以防止每个输入重复信息。

<form id="myform">
<table>
    <tr>
        <td><input name="currency1" class="required" unique="currency"/></td>
    </tr>
    <tr>
        <td><input name="currency2" class="required" unique="currency"/></td>
    </tr>
    <tr>
        <td><input name="currency3" class="required" unique="currency"/></td>
    </tr>
    <tr>
        <td><input name="currency4" class="required" unique="currency"/></td>
    </tr>
</table>

这是函数

jQuery.validator.addMethod("unique", function(value, element, params) {
     var prefix = params;
     var selector = jQuery.validator.format("[name!='{0}'][name^='{1}'][unique='{1}']", element.name, prefix);
     var matches = new Array();
     $(selector).each(function(index, item) {
         if (value == $(item).val()) {
             matches.push(item);
         }
     });

     return matches.length == 0;
          }, 
       "Valor Repetido"
     );


     jQuery.validator.classRuleSettings.unique = {
          unique: true
     };

     $("#myform").validate();

     $("#validate").onBlur(function() {
          $("#myform").valid();
     });

和 CSS

label.error { color: red }

谁能帮帮我?

【问题讨论】:

  • 您能告诉我您使用 jquery 验证什么。我认为用户的输入我是对还是错..?
  • 这个表单验证了很多产品是一个包的一部分,这些产品不能在同一个包中重复自己

标签: javascript jquery angularjs directive no-duplicates


【解决方案1】:

您可以拥有一个对象数组来保存所有值,并仔细观察。
在控制器中:

$scope.currencies =
    [{'value':'val1'},{'value':'val2'},{'value':'val1'} ];

$scope.$watch('currencies', function(){
    $scope.duplicates = false;
    var found = [];
    $scope.currencies.forEach(function(currency){
        if(!(found.indexOf(currency.value)+1))
            found.push(currency.value);
        else $scope.duplicates = true;
    });
},true); //The 'true' last parameter is the signal to deep watch.

表中的每个输入都与ng-model 绑定到$scope.currencies 中的一个对象,以便深度监视可以立即看到任何更改。您可以使用ng-repeat 指令生成输入列表:

<tr ng-repeat="currency in currencies">
    <td><input type="text" ng-model="currency.value"></input></td>
</tr>

然后对于提交按钮,有&lt;input type="submit" ng-disabled="duplicates"&gt;&lt;/input&gt;

如果您愿意,您可以添加按钮以在$scope.currencies 中添加或删除元素,它会立即反映在视图中。

Plunker sample

【讨论】:

  • 那么,我怎样才能将每个输入放入 $scope.currencies? by name="currency1" by id= 或 by class="" 我不明白...
  • 您将使用 ng-model 属性将您的输入绑定到您的 JS 变量。当一个更新时,另一个会自动更新。我已经稍微更新了答案以使其更加明显。
  • 我确实运行了这段代码,但无论我在每个输入中输入什么,提交按钮总是处于禁用状态
  • 我在我的示例中进行了更正,并包含了一个有效的 Plunker 示例。
  • 非常感谢你能帮我找到更多关于自定义指令的例子来练习更多吗?再次感谢您
猜你喜欢
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-19
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 2013-06-10
相关资源
最近更新 更多